I have a form with some quantity field and a plus and minus sign on each side,
First of all, type="submit"
should be type="button"
in all cases. Also, you cannot have two elements with the same ID; I assume you want add1
, minus1
, add2
, minus2
, etc.
The following jQuery code should work great.
$(function () {
var numButtons = 10;
for (var i = 1; i <= numButtons; ++i) {
$("#add" + i).click(function () {
var currentVal = parseInt($("#qty" + i).val());
if (!isNaN(currentVal)) {
$("#qty" + i).val(currentVal + 1);
}
});
$("#minus" + i).click(function () {
var currentVal = parseInt($("qty" + i).val());
if (!isNaN(currentVal) && currentVal > 0) {
$("#qty" + i).val(currentVal - 1);
}
});
}
});
Worth noting:
$(function() { ... })
call so that you attach the event handlers only after the page loads. (Specifically, after the DomContentLoaded
event.) This prevents errors about how an object with the ID "add1" doesn't exist or whatever, because technically that object doesn't exist until the page actually loads.NaN
handles the case of the user typing non-numeric stuff into the field. You could add your own logic for that in particular, e.g. auto-convert non-numeric properties to 0 whenever someone clicks add or minus.You should use unique id's for all your inputs, e.g. qty1_add
, qty1_minus
.
Then you can attach the click event to these buttons:
$("#qty1_add").click( function() {
$("#qty1").val( parseInt($("#qty1").val()) + 1);
}).