69

I am having some trouble with an if statement. I want to set num to 0 of NaN:

$('input').keyup(function() {

var tal = $(this).val();
var num = $(this).data('boks');
if(isNaN(tal)) {
var tal = 0;
}
});
3

2 Answers 2

148

You have to assign the value back to $(this):

$('input').keyup(function() {

var tal = $(this).val();
var num = $(this).data('boks');
if(isNaN(tal)) {
var tal = 0;
}
$(this).data('boks', tal);
});

nicely written:

$('input').keyup(function() {
    var eThis = $(this);
    var eVal = (isNaN(eThis.val())) ? 0 : eThis.val();
    eThis.data('boks', eVal);
});
2
  • eThis.val() is a String the 0 is a Number. Also you are using the global isNaN which is different from the better practice Number.isNaN (and its respective 1 liner polyfil). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Mar 29, 2015 at 5:16
  • Your solution did not work for me then i used var tal = parseInt($(this).val()) || 0; it worked.
    – Kamlesh
    Oct 3, 2019 at 11:13
53

If you want replace the NaN with 0, just write this:

var tal = parseInt($(this).val()) || 0;
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.