Tasos
Tasos

Reputation: 7577

Change input number with jQuery and a click on a button

I have the following HTML code

<span id="bedrooms-minus" class="filter_sign">-</span>
<input type="number" min="0" max="10" id="bedrooms" value="1"/>
<span id="bedrooms-plus" class="filter_sign">+</span>

What I try to do, is to increase/decrease the value of the input by one whenever someone clicks on the +/- buttons on the sides of the input.

This is the jquery code I am working on

  $("#bedrooms-minus,#bedrooms-plus").click(function(){
        var value = parseInt($("#bedrooms").val(), 10);
        $("#bedrooms").val(value + $(this).is("#bedrooms-minus") ? -1 : 1);
    });

However, when I click on it, instead of updating the value it just changes it with -1 or 1.

Here is a jsfiddle with the replication of the bug

https://jsfiddle.net/ug395zck/

Upvotes: 0

Views: 101

Answers (1)

Trupti Shetty
Trupti Shetty

Reputation: 66

Based on operation precedence, + will be evaluated 1st & then the conditional operator. Hence you end-up getting 1 or -1. Add brackets before adding 1 or -1.

$("#bedrooms-minus,#bedrooms-plus").click(function(){
        var value = parseInt($("#bedrooms").val(), 10);
        $("#bedrooms").val(value + ($(this).is("#bedrooms-minus") ? -1 : 1));
    });

Also, when 'input' is 'number' you don't need those 2 buttons. Up Arrow Key & Down arrow key will increment & decrement the number respectively

Upvotes: 2

Related Questions