Domanda

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());
    }
});
È stato utile?

Soluzione

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

Altri suggerimenti

$('#myInput').val().length < 0 when will a length of a string be less than zero?

parseInt($('#myInput').val()) + $('#myInput').val() this doesn't actually do numeric addition, if th value is the string 1 then it will be like doing 1+"1" which will return 11

I think what you're looking for is :

$('.switch').click(function () {
            var val = parseInt($('#myInput').val());
            $('#myInput').val(-val);
    });

see here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top