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 = 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>
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);
});
Let me try your original keyup code .ends
,I just want to explain how is work below code
.starts
,we currently in tr>td>input
,so need backup to tr
by parent()
then we find .starts
inside its elements.As also .ends
find .studen
is also in state tr>td>input
,so backup to td
and go next 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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With