Rails beginner
Rails beginner

Reputation: 14504

jQuery If value is NaN

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

Upvotes: 69

Views: 216733

Answers (2)

mreq
mreq

Reputation: 6542

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

Upvotes: 150

DANDYYeah
DANDYYeah

Reputation: 695

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

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

Upvotes: 55

Related Questions