简体   繁体   中英

Dynamically increase and decrease numbers in JavaScript

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 "+"?

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;
}

http://jsfiddle.net/VY9tE/

One more example with your html form and with check count(0..99):

http://jsfiddle.net/VY9tE/2/

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.

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);
    });
});

See it in action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM