I have a form with some quantity field and a plus and minus sign on each side,
<form id="myform">
product1
<input type="submit" value="+" id="add">
<input type="text" id="qty1">
<input type="submit value="-" id="minus">
product2
<input type="submit" value="+" id="add">
<input type="text" id="qty2">
<input type="submit value="-" id="minus">
</form>
I'd like to increase the value of the field by one if the add button is pressed and decrease by one if minus is pressed. Also the value shouldn't get less than 0.
Is there a way to do this in jQuery?
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.Your html isn't quite valid, you have multiple elements with the same id, it should be unique. But lets say you only had one set of inputs/buttons:
$("#add").click(function(){
var newQty = +($("#qty1").val()) + 1;
$("#qty1").val(newQty);
});
$("#minus").click(function(){
var newQty = +($("#qty1").val()) - 1;
if(newQty < 0)newQty = 0;
$("#qty1").val(newQty);
});
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