Reputation: 21
I would like to know how to dynamically increase and decrease numbers in JavaScript. The users buys an item and I have a input field "quantity" with a number and two buttons: One to add and another to remove.
My code is the following
<td class="quantity">
<a href="#" class="removeItem">-</a>
<input type="text" id="purchase_quantity" min="1" max="99" delta="0" cost="<?php echo$poupa ?>" name="purchase_quantity" value="1" />
<a href="#" class="addItem" >+</a>
</td>
How can I have it decrease the number of the input field when I click on the "-" and increase the number of the input field when clicking on the "+"?
Upvotes: 1
Views: 3956
Reputation: 10599
Markup (changed the ID on the text input to a class):
<td class="quantity">
<a href="#" class="removeItem">-</a>
<input type="text" class="purchase_quantity" min="1" max="99" delta="0" cost="" name="purchase_quantity" value="1" />
<a href="#" class="addItem">+</a>
</td>
JavaScript (uses jQuery):
$(function() {
$('.removeItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Not allowed to go below zero
if (currentQuantity > 0) {
// Update input with decreased quantity
$(target).val(--currentQuantity);
}
});
$('.addItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Update input with increased quantity
$(target).val(++currentQuantity);
});
});
Upvotes: 0
Reputation: 1479
var input = document.getElementById("YOUR_INPUT_ID");
function minus(){
var num = +input.value;//+ for convert from string to number
num--;
input.value = num;
}
function plus(){
var num = +input.value;//+ for convert from string to number
num++;
input.value = num;
}
One more example with your html form and with check count(0..99):
Upvotes: 1
Reputation: 347
decrease:
<a href="#" class="removeItem" onclick="$('#purchase_quantity').val($('#purchase_quantity').val()-1); return false;">-</a>
increase
<a href="#" class="addItem" onclick="$('#purchase_quantity').val($('#purchase_quantity').val()+1); return false;">+</a>
Assuming you can use jquery since you have it tagged.
Upvotes: 0