Computed JavaScript Field

I just don’t see what I am doing wrong ... It does not evaluate the "stunden" field.

For my part, there is a small mistake, and I just do not see it.

EDITED: now everything works 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 = ends - starts; $(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> 
+7
javascript
source share
2 answers

The problem is that you recount when the key is pressed in the .stunden fields, so you have to move the event to other inputs or the parent line. You will 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); }); 
+5
source share

Let me try your source code for .ends keys, I just want to explain how below code works

  • call .starts , we are currently in tr>td>input , so you need to backup tr to parent() , after which we will find .starts inside our elements. And also .ends
  • find .studen also in the tr>td>input state, so back up to td and move on to td by next (), then find .studen .

     $(document).ready(function(){ $('.ends').keyup(function(){ var starts = 0; var ends = 0; var stunden = 0; if (!isNaN($(this).parent().parent().find(".starts").val())) { starts = $(this).parent().parent().find(".starts").val(); } if (!isNaN($(this).parent().parent().find(".ends").val())) { ends = $(this).parent().parent().find(".ends").val(); } stunden = starts - ends; $(this).parent().next().find('.stunden').val(stunden); }); }); 
+1
source share

All Articles