javascriptjquerynumeric-keypad

when pressed wil ++ or -- a value, numeric keypad


Using numeric keypad I have added a .switch handler which when clicked will bring the value back to '0' (test purpose only)

If the value is +32 and the button is pressed I would like it to change to -32, vice versa.

so far I have only gotten it to return to 0, i was thinking then deleting or adding the val again, even tried -- $('#myInput').val());

$('.switch').click(function () {
    if (!isNaN($('#myInput').val()) && $('#myInput').val().length > 0) {
        $('#myInput').val(parseInt($('#myInput').val()) - $('#myInput').val());
    }
    if (!isNaN($('#myInput').val()) && $('#myInput').val().length < 0) {
        $('#myInput').val(parseInt($('#myInput').val()) + $('#myInput').val());
    }
});

Solution

  • If all you're trying to do is switch back and forth between a positive/negative number you can make your code much simpler and lose all the if conditions:

    $('.switch').click(function () {
        var $input = $('#myInput');
        $input.val() != "" && !isNaN($input.val()) && $input.val(-$input.val());
    });
    

    This is the equivalent of multiplying the number by -1, which will have the same effect.

    Example fiddle