【问题标题】:jquery check if value is not null / empty or NaNjquery检查值是否不为空/空或NaN
【发布时间】:2015-09-16 22:45:38
【问题描述】:

我目前正在使用 jQuery 检查 value 是否为 Nan,并希望将检查扩展到非 null 或空,但不确定如何执行此操作, 这是我的代码;

<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)) {
  • 如果认为他可能想要if(!this.value || isNaN(this.value)),换句话说,如果它为 null 或 NAN
  • @BenRobinson 是的,已经编辑过了。 :-)

标签: jquery asp.net


【解决方案1】:

你可以改变:

if(isNaN(this.value)) 

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

但是你为什么不使用:

jQuery.isNumeric?

所以:

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

【讨论】:

    【解决方案2】:

    你可以像这样直接检查 null

    (myVar !== null)

    检查变量是否为空,你可以这样做

    (myVar !== '')

    对于数字检查,使用isNaN()$.isNumeric() 可能有效,但$.isNumeric() 返回更准确的布尔值read more here

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

    大家一起

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

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2011-11-04
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多