Reputation: 35
I am looking for way to display error button when the sum of entered numbers to input fields is less or more than 8.The input fields are located in an HTML table that is generated by the PHP loop.
I wrote this code HTML in loop:
<tr class="new_row">
<td>employee 1</td>
<td><input class="position1" type="text" value="8" placeholder="8"/></td>
<td><input class="position2" type="text" value="0" placeholder="0"/></td>
<td><input class="total" type="text" placeholder="8" disabled/></td>
<td class="ee"> </td>
</tr>
And JS
$('input').on('change', function () {
var scope = $(this).closest('.new_row'),
pos1 = $('.position1', scope).val(),
pos2 = $('.position2', scope).val(),
total = $('.total', scope),
error = $('.error', scope);
if ($.isNumeric(pos1) && $.isNumeric(pos2)) {
var suma = Number(pos2)+ Number(pos1);
if(suma !== 8)
{
var r= $("<a href='#' class='btn btn-danger mr5 mb10' >!!!</a>");
$(".ee").append(r);
total.val(suma + 'h');
}else
{
error.val("ok");
total.val(suma + 'h');
}
} else {
total.val('');
}
});
And here there are two problems. 1) The error button appears and remains visible when the condition is not met. And more have been added. I want the error button to disappear after the user corrects the data. 2) The error button appears in each row. Even in those in which the sum equals 8. And I want the JS code to take only data from each row separately.
Upvotes: 0
Views: 38
Reputation: 3324
Check following code. Demo available https://jsfiddle.net/xpvt214o/126161/
//bind recalculate function to row
$(".new_row").on("recalculate", function(){
var scope = $(this);
//clear previous error, if exist
scope.find(".ee").html("");
var sum = 0;
//or find all inputs, exclude total, f.e. .find("input:not(.total)")
scope.find(".position1, .position2").each(function(){
var val = parseInt($(this).val());
if(!isNaN(val)){
sum += val;
}else{
sum = undefined;
}
});
//set total to input
scope.find(".total").val(!!sum ? (sum + "h") : '');
if(sum !== 8){
//add error
scope.find(".ee").append(
$("<a href='#' class='btn btn-danger mr5 mb10' >!!!</a>")
);
}
}).trigger("recalculate");
//detect field change
$('.new_row input').on('change', function () {
$(this).closest(".new_row").trigger("recalculate");
});
Upvotes: 1