jquery检查value是否为null / empty或NaN



我目前正在检查是否使用jQuery值为Nan,并希望将检查扩展到不为空或空,但不确定如何做到这一点,这是我的代码;

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

您可以更改:

if(isNaN(this.value)) 

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

但是为什么不使用:

jQuery。isNumeric ?

So:

if(!jQuery.isNumeric(this.value)) {
            alert("Please ensure the quantity specified is numeric");
            $(this).val("1");
        }
        else{
            $(this).val(this.value);
        }

你可以直接检查null

(myVar !== null)

检查变量是否为空,可以执行

(myVar !== '')

对于数字检查,使用isNaN()$.isNumeric()都可以工作,但$.isNumeric()返回更精确的布尔值

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

all together

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

最新更新