Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } }); 
like image 703
Rails beginner Avatar asked Feb 16 '12 12:02

Rails beginner


People also ask

How can I check if a number is NaN in jquery?

The isNaN() method returns true if a value is NaN.

How do you know if a variable is NaN?

isNaN() Method: To determine whether a number is NaN, we can use the isNaN() function. It is a boolean function that returns true if a number is NaN otherwise returns false.

How check value is null or not in jquery?

You can use exclamation mark ! to check if it is null. The above code means that if the $('#person_data[document_type]') has no value (if the value is null).

How check string is empty or null in jquery?

Answer: Use the === Operator You can use the strict equality operator ( === ) to check whether a string is empty or not.


1 Answers

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); }); 
like image 55
mreq Avatar answered Sep 28 '22 22:09

mreq