-1
<input id='inpa' type='number' value=1>

js

var inp = $('#inpa').val();

$('#btnext').click(function(){
    $('#inpa').val(inp + 1);
    $('#inpa').val(inp += 1); // also tried
});

in both cases result is 11!

how can I get 2 ?

qadenza
  • 7,864
  • 17
  • 50
  • 92

4 Answers4

1

You have to parse them into numbers first:

var a = parseInt($('#inpa').val(), 10);
SANM2009
  • 1,439
  • 2
  • 10
  • 25
1

The value of HTML inputs are always strings. You need to ‘parse’ the number as an integer.

parseint(inp)

will understand whatever inp is as an integer, which you can now +1 and -1 from.

When you set the value of the tag, it will change it back to a string for you.

Thomas Edwards
  • 10,796
  • 3
  • 18
  • 38
1

You have to convert string to number using Number or parseInt

$('#btnext').click(function() {
  var inp = Number( $('#inpa').val() ); /* Need to be inside the function, so that will get the updated value every user click*/
  $('#inpa').val(inp + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='inpa' type='number' value=1>
<input type="button" id="btnext" value="btnext">
Eddie
  • 25,279
  • 6
  • 26
  • 53
1

Your code concatenates strings.

You need to convert each variable to a number by calling parseFloat() around each one.

$('#btnext').click(function(){
   var inp = $('#inpa').val();
    $('#inpa').val(parseInt(inp) + 1);
   // $('#inpa').val(inp += 1); // also tried
});
Léo R.
  • 3,041
  • 1
  • 8
  • 21