Reputation: 1242
I've got some javascript to change the input value via plus/minus buttons. I now need to save the value after the value has been decremented in a variable and output it as a number.
The javascript for the decrement looks something like this:
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
var test = parseInt($('input[id='+fieldName+']').val(currentVal - 1).val());
alert(test);
}
So as you can see I'm trying to get the updated value of the input in a variable called 'test', but all I'm getting is a NaN. Any ideas how to output the updated value of the input as a number within my test variable?
Upvotes: 0
Views: 171
Reputation: 487
Something showed up to me.
You are using jquery (I think it's right cause of the $ selector), and you are getting the ID with bracket notation. Why not using something like
var selector = '#' + fieldName;
Then
$(selector)???
Another thing, usually when I'm trying something with javascript, I try it into the developer tool's console of my browser. Doing it step by step avoid mistakes
Upvotes: 0
Reputation: 4557
You can use double Tilda operator ~~
which behaves like Math.floor()
except will return you 0
if the value is not a number.
I believe this is the solution you are looking for:
let inputField = document.querySelector('input[name="fieldName"]');
increment = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
inputField.value = currentValue + 1;
};
decrement = () => {
let currentValue = ~~inputField.value;
alert(currentValue);
if (currentValue > 0) {
inputField.value = currentValue - 1;
}
};
<input type="number" name="fieldName" value="0" />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
Hope this helps,
Upvotes: 0
Reputation: 2148
As @trincot said we cannot re-produce your situation. But the reason a NaN would be returned is because.
parseInt
Returns an integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
let a = '1'
let b = 'Two'
console.log(parseInt(a));
// 1
console.log(parseInt(b));
// NaN
console.log(parseInt(undefined))
// NaN
Upvotes: 1