lewis4u lewis4u - 6 months ago 17
Javascript Question

JavaScript calculated field

I just can't see what am I doing wrong... It doesn't calculate the "stunden" field.

There is some small mistake from my side and I just can't see it.

EDITED: now all is working as it should



$(document).ready(function(){
$('.item').keyup(function(){

var starts = 0;
var ends = 0;
var stunden = 0;

if (!isNaN($(this).find(".starts").val())) {
starts = $(this).find(".starts").val();
}
if (!isNaN($(this).find(".ends").val())) {
ends = $(this).find(".ends").val();
}

stunden = starts - ends;
$(this).find(".stunden").val(stunden);

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table id="t1" class="table table-hover">
<tr>
<th class="text-center">Start Time</th>
<th class="text-center">End Time</th>
<th class="text-center">Stunden</th>
</tr>
<tr id="row1" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
<tr id="row2" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
</table>
</div>




Answer

The problem is that you are recalculating when a key is pressed in the .stunden fields, so you should move the event to the other inputs, or the parent row. You'll need something like this.

$('.item').keyup(function(){
  var starts = 0;
  var ends = 0;
  var stunden = 0;
  if (!isNaN($(this).find(".starts").val())) {
    starts = $(this).find(".starts").val();
  }
  if (!isNaN($(this).find(".ends").val())) {
    ends = $(this).find(".ends").val();
  }
  stunden = starts - ends;
  $(this).find(".stunden").val(stunden);
});