0

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?

MariaL
  • 1,112
  • 2
  • 16
  • 41
  • 1
    I cannot reproduce your issue. Could you add concrete values for `fieldName` and `currentVal` and add the corresponding HTML? – trincot Apr 01 '19 at 21:17
  • 1
    The variable you are calling parseInt on must be incorrect, possibly undefined. – ABC Apr 01 '19 at 21:20

3 Answers3

1

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
ABC
  • 2,068
  • 1
  • 10
  • 21
0

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,

Community
  • 1
  • 1
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
0

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

r0ulito
  • 487
  • 2
  • 13