2

Тип данных в input.value должен приводиться к числу через parseInt, но не срабатывает. Как привести к числу вводимые данные?

let pallets = document.getElementsByClassName('pallets');
let totalPallets = document.getElementById('totalPallets');

for(let i=0; i < pallets.length; i++) { pallets[i].addEventListener('input', function(event){ let num = parseInt(pallets[i].value); console.log('total: ' + totalPallets.value); console.log('current: ' + pallets[i].value); console.log('total = ' + totalPallets.value - num); }) }

div {
  width: 200px;
}
div input {
  margin-bottom: 5px;
}
<div>
  <input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" id="totalPallets" value="33">

</div>
Alex
  • 1,122
  • 6
  • 18

2 Answers2

3

На самом деле все приводится.

Проблема в строке:

console.log('total = ' + totalPallets.value - num);

так как не расставлены скобки сначала выполняется +, получается строка: "total=33" из-за этого при попытке привести это значение к числу получается NaN.

Для решения достаточно просто расставить скобки:

console.log('total = ' + (totalPallets.value - num));

let pallets = document.getElementsByClassName('pallets');
let totalPallets = document.getElementById('totalPallets');

for (let i = 0; i < pallets.length; i++) { pallets[i].addEventListener('input', function(event) { let num = parseInt(pallets[i].value); console.log('total: ' + totalPallets.value); console.log('current: ' + pallets[i].value); console.log('total = ' + (totalPallets.value - num)); }) }

div {
  width: 200px;
}

div input {
  margin-bottom: 5px;
}
<div>
  <input type="text" class="pallets">
  <input type="text" class="pallets">
  <input type="text" class="pallets">
  <input type="text" class="pallets">
  <input type="text" class="pallets">
  <input type="text" id="totalPallets" value="33">

</div>
Grundy
  • 81,538
1

let pallets = $('.pallets');
let totalPallets = $('#totalPallets');

$(pallets).on('input', (event) => { console.log($(event.currentTarget).val()); console.log('total:', typeof +totalPallets.val()); console.log('current', typeof +$(event.currentTarget).val()); console.log('total =', typeof (+totalPallets.val() -$(event.currentTarget).val())); })

div {
  width: 200px;
}
div input {
  margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" class="pallets">
<input type="text" id="totalPallets" value="33">

</div>
  • Это решение на jQuery. Мне нужно на чистом JS. – Alex Dec 22 '18 at 08:49
  • Перепишите на javascript если вам нужно, но смысл тут совсем не в выборе DOM элементов, а в операциях в console.log – Никита Лощенин Dec 22 '18 at 08:54