0

I have the following code:

$("#negativecustomnicotinevgInput, 
#positivecustomnicotinevgInput").click(function(){
  if($(this).attr("id") == "negativecustomnicotinevgInput"){
      $("#customnicotinepgInput").val($("#customnicotinepgInput").val()+5);
  }
  else if($(this).attr("id") == "positivecustomnicotinevgInput"){
    $("#customnicotinepgInput").val($("#customnicotinepgInput").val()-5);
  }
});

When I click on the button positivecustomnicotinevgInput this reduces the value by 5. However, when clicking on negativecustomnicotinevgInput this actually concatenates the number 5 rather than adding it to the value.

For example, the value 50 becomes 505 then 5055 rather than the expected 55 and 60 by adding 5.

A. Fletcher
  • 103
  • 6
  • if they are integers, you should parse them first: `parseInt($("#customnicotinepgInput").val())` otherwise it will treat the value as text (and concatenate the number) – Pete Jan 08 '19 at 11:00

2 Answers2

1

the + is used for string concatenation too. When using -, JS does a conversion from the string of an input (containing a number) to a number. When using +, js doesn't necessary does this conversion.

To fix that behaviour, you can force a conversion, using parseInt() this in example :

$("#customnicotinepgInput").val(parseInt($("#customnicotinepgInput").val(), 10) + 5);
//                              ^-------^-------------------------------------^-------Notice this
Cid
  • 14,968
  • 4
  • 30
  • 45
  • Thats fixed the problem! I totally forgot that input boxes could be interpreted as strings. As soon as I gain enough rep i'll up vote the answer. Thanks for the help – A. Fletcher Jan 08 '19 at 11:03
0

be a bit more diligent about checking the values

$("#negativecustomnicotinevgInput, #positivecustomnicotinevgInput").click(function(){
    let n = Number( $("#customnicotinepgInput").val());
    let id = $(this).attr("id");

    if ( isNaN( n)) n = 0;  // make sure it's a number

    if( id == "negativecustomnicotinevgInput"){
        $("#customnicotinepgInput").val(n+5);
    }
    else if( id == "positivecustomnicotinevgInput"){
        $("#customnicotinepgInput").val(n-5);

    }

});
David Bray
  • 566
  • 1
  • 3
  • 15