3

sI'm currently checking if value is Nan using jQuery and would like to extend the check to not null or empty as well but not sure on how to do this, here's my code;

<script type="text/javascript"> // ensure quantity textbox is numeric
$(document).ready(function () {
    $('[id$=txtQuantity]').change(function () {
        if(isNaN(this.value)) {
            alert("Please ensure the quantity specified is numeric");
            $(this).val("1");
        }
        else{
            $(this).val(this.value);
        }
    });
});

3
  • Change if(isNaN(this.value)) { to if(!this.value || isNaN(this.value)) { Commented Sep 16, 2015 at 14:17
  • If think he probably wants if(!this.value || isNaN(this.value)) in other words if its null or a NAN Commented Sep 16, 2015 at 14:19
  • @BenRobinson yes already edited. :-) Commented Sep 16, 2015 at 14:19

2 Answers 2

6

You can change :

if(isNaN(this.value)) 

To

if(!this.value || isNaN(this.value)) ...

But why don't you use :

jQuery.isNumeric ?

So :

if(!jQuery.isNumeric(this.value)) {
            alert("Please ensure the quantity specified is numeric");
            $(this).val("1");
        }
        else{
            $(this).val(this.value);
        }
Sign up to request clarification or add additional context in comments.

Comments

4

you can check for null directly like

(myVar !== null)

to check if the variable is empty you can do

(myVar !== '')

and for the numeric check either using isNaN() or $.isNumeric() may work but $.isNumeric() return more accurate boolean read more here

(isNaN(myVar)) or (!$.isNumeric(myVar))

all together

if ( (myVar !== null) || (myVar !== '') || (!$.isNumeric(myVar)) ){ ... }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.