I have several Input-Boxes that are not present on first page load. They are created by JQuery via .clone().
<input type="text" class="myInputs" name="input[0]" />
<input type="text" class="myInputs" name="input[1]" />
<input id="remove" type="button" value="Remove last input">
Then I’ve a function to sum up all these fields and make an alert with the result, which is called by
a) an onchange function for the input fields (works like a charm) and
b) a “remove one of the input fields”-button that should remove one field and then call the function again.
$(document).ready( function() {
function calculatesum() {
var sum = 0;
var value = 0;
var error = false;
var count = new Number($("input.myInputs").length);
if(count >= 1) {
$("input.myInputs").each(function() {
if($.isNumeric($(this).val())) {
value = new Number($(this).val());
sum = sum + value;
}
else
error = true;
});
}
if(!error) alert(sum);
else alert("Error");
}
$('body').on('change', 'input.myInputs', function () {
calculatesum();
});
$('#remove').click(function () {
if (confirm("Are you sure?")) {
$('.myInputs:last').slideUp('slow', function () {
$(this).remove();
});
calculatesum();
}
return false;
});
}
Now the point is, after removing the element via the button-function, it still gets the (previously deleted) input field and its value.
How can I prevent that?
You should use .on instead of click at the below code fragment, like this