jQuery If value is NaN

JavascriptJquery

Javascript Problem Overview


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;
}
});

Javascript Solutions


Solution 1 - Javascript

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);
});

Solution 2 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRails beginnerView Question on Stackoverflow
Solution 1 - JavascriptmreqView Answer on Stackoverflow
Solution 2 - JavascriptDANDYYeahView Answer on Stackoverflow