简体   繁体   中英

Increment the value of an input type number using jQuery

I'm trying to increment the value of an input type="number" element using jQuery . However I currently have it so that every time I press the add button it appends 1 to the value so I get a value like 1111 etc etc...

I was able to do it fine when it was set to type=text but it was not ideal as I was trying to increment the values so all that was happening was the counter was being appended to the value of the input box. Output was like this 01 02 03 04 .

Anyways, Currently I'm doing this:

HTML

<input type="number" class="qty" id="book-qty"  disabled/>
<span class="add">ADD</span>

jQuery

var count = 0;
$('.minus').click(function () {

    if (count - 1 >= 0) {
        count = parseInt($(this).parent().find('#book-qty').val());
        count = count - 1;
    $(this).parent().find('#book-qty').val(count);
    } else {
        alert('Nothing to take away!');
    }
});
$('.add').click(function () {
    count = $(this).parent().find('#book-qty').val();
    count = count + 1;
    $(this).parent().find('#book-qty').val(count);
});

I've a jsFiddle I'm working on here:

https://jsfiddle.net/javacadabra/L1sLr921/

Does anyone know?

jsfiddle demo

you need to parse the value to an integer otherwise it get treated as a string so it will concatenate instead of add together.

count = parseInt($('#book-qty').val());

Also you need to specify a default value for your inputs like stated by Mex.

Set the default value to 0 with "value=0" on the input type=number.

Then use:

count = parseInt(count) + 1;

instead of:

count = count + 1;

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