<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
?
<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
?
You have to parse them into numbers first:
var a = parseInt($('#inpa').val(), 10);
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.
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">
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
});