Chris Clark Chris Clark - 8 months ago 12
Javascript Question

.change() Jquery not working

I have a series of elements with class

xyz
. The requirement is a user needs to input one number in them only. I then need to concat them. For example, their meter would read
1
2
0
0
.

I have below.

$('.xyz').change(function () {
console.log($(this));
arrayNums.length = 0;
var thisRead = parseInt(CombinedNumber(arrayNums), 10);
var lastRead = parseInt($('.abcd').html(), 10);
if ((thisRead - lastRead) <= 1) {
$('#idthing').html("Your Last reading compared to this reading is " + (thisRead - lastRead) + " KWH <br>Are you SURE you want to submit this Reading?");
$('#idthing').attr('style' , 'color: red !important');
}
else { $('#idthing').text(thisRead - lastRead + ' KWH');}
});

function CombinedNumber(arrayNums) {
combined = "";
$('.xyz').each(function (index) {
arrayNums.push($(this).val());
});
$.each(arrayNums, function (index, value) {
combined += value;
});
console.log(combined);
return combined


This works the first time, if the user clicks off of the area, before hitting the submit button, but they might hit the submit button first.
Additionally, it ceases to do the calculation after the first time it happens!

I am trying to get a responsive calculation each time someone enters a number. Here is the DOM portion.

<div>
<ul>
<li>
<input class="xyz">
</li>
<li>
<input class="xyz">
</li>
</ul>
</div>

Answer

Use input event instead of change as change handler will be invoked only when focus of the element is lost.

var arrayNums = [];
$('.xyz').on('input', function() {
  console.log($(this));
  arrayNums.length = 0;
  var thisRead = parseInt(CombinedNumber(arrayNums), 10);
  var lastRead = parseInt($('.abcd').html(), 10);
  if ((thisRead - lastRead) <= 1) {
    $('#idthing').html("Your Last reading compared to this reading is " + (thisRead - lastRead) + " KWH <br>Are you SURE you want to submit this Reading?");
    $('#idthing').attr('style', 'color: red !important');
  } else {
    $('#idthing').text(thisRead - lastRead + ' KWH');
  }
});

function CombinedNumber(arrayNums) {
  combined = "";
  $('.xyz').each(function(index) {
    arrayNums.push($(this).val());
  });
  $.each(arrayNums, function(index, value) {
    combined += value;
  });
  console.log(combined);
  return combined;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
  <ul>
    <li>
      <input class="xyz">
    </li>
    <li>
      <input class="xyz">
    </li>
  </ul>
</div>