Search code examples
jqueryinputonblur

In JQuery how to add 1 to the value of quantity input field if quantity >= 10


I have a form field id quantity that I need to check what number is entered. If the number is >= 10 I need to add 1 to the quantity field.

i.e. buy 10 get 1 free.

I came across this jquery snippet and thought I would be able to adjust it.

$('input#quantity').on('blur', function() {
    // on blur, if there is no value, set the defaultText
    if ($(this).val()=='') $(this).val($(this).data('defaultText'));
}); 

after some comments i have adjusted the code to this:

$('input.input').on('blur', function() {
    // on blur, if there is no value, set the defaultText
    if ($(this).val()>=10) $(this).val($(this).val()+1);;
});

the problem now is if you type 12 the value changes to 121


Solution

  • the problem now is if you type 12 the value changes to 121

    $(this).val( parseInt($(this).val()) + 1 );
    

    Use parseInt