JS1986
JS1986

Reputation: 1950

jquery element click event only allowed once? confuddled

One a click event of an element, it only works once. Say the value is 2 it will increase/decrease/reset only once.

How to I reset the event so the user can keep clicking on the element increasing the value of the value .item-selection-amount

$('.item-selection-amount').click(function(event) {
        var amount = $(this).val();
        switch (event.which) {
            case 1:
                //set new value +
                $(this).val(amount + 1);
                break;
            case 2:
                //set new value reset
                $(this).val(0);
                break;
            case 3:
                //set new value -
                if(amount > 0){ 
                    $(this).val(amount - 1);
                }
                break;
        }
    });

Thanks

Upvotes: 0

Views: 381

Answers (1)

alex
alex

Reputation: 490497

JavaScript cleverly (read: it was a bad idea) overloaded the + operator to mean arithmetic addition and string concatenation.

If one of the operands looks like a string, it will do string concatenation. Your value looks like a string, so it does that.

I have used parseInt(val, 10) to try and get the integer, or get 0 if we get back something like NaN (not a number). The second argument to parseInt() is the radix. Without that, a number entered as 072 will be read in octal (base 8) format and probably not what yo want.

$('.item-selection-amount').click(function(event) {
        var amount = parseInt($(this).val(), 10) || 0;
        switch (event.which) {
            case 1:
                //set new value +
                $(this).val(amount + 1);
                break;
            case 2:
                //set new value reset
                $(this).val(0);
                break;
            case 3:
                //set new value -
                if(amount > 0){ 
                    $(this).val(amount - 1);
                }
                break;
        }
});

jsFiddle.

Update

The right click event, case 3, would not work for me with Chrome, so I binded it to the contextmenu event and it worked...

$('.item-selection-amount').click(function(event) {
    var amount = parseInt($(this).val(), 10) || 0;
    switch (event.which) {
    case 1:
        //set new value +
        $(this).val(amount + 1);
        break;
    case 2:
        //set new value reset
        $(this).val(0);
        break;
    case 3:
        //set new value -
        if (amount > 0) {
            $(this).val(amount - 1);
        }
        break;
    }
}).bind('contextmenu', function(event) {
    event.preventDefault();
    var amount = parseInt($(this).val(), 10) || 0;
    if (amount > 0) {
        $(this).val(amount - 1);
    }
})

jsFiddle.

Upvotes: 2

Related Questions