【问题标题】:jQuery - simple input validation - "empty" and "not empty"jQuery - 简单的输入验证 - “空”和“非空”
【发布时间】:2011-07-23 15:43:36
【问题描述】:

我有一个要验证的输入:

<input type="text" id="input" />

这是 JS:

        jQuery("#input").live('change', function() {

            if("#input:not(:empty)") {
                alert('not empty');
            }   

            else if("#input:empty") {
                alert('empty'); 
            }
        });

即使“#input”为空,也无法显示带有“empty”消息的警报。所以,基本上,无论我做什么,只有第一个陈述是真的,第二个是假的,总是。

怎么了?

【问题讨论】:

标签: jquery ajax validation


【解决方案1】:

JQuery's :empty selector 选择页面上所有为空的元素,因为它们没有子元素,包括文本节点,而不是所有没有文本的输入在他们里面。

Jquery: How to check if an input element has not been filled in.

这是从上述线程中窃取的代码:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

之所以可行,是因为 JavaScript 中的空字符串是一个“假值”,这基本上意味着如果您尝试将其用作布尔值,它将始终评估为 false。如果需要,可以将条件更改为 $(this).val() === '' 以增加清晰度。 :D

【讨论】:

    【解决方案2】:

    你可以这样做

    $("#input").blur(function(){
        if($(this).val() == ''){
            alert('empty'); 
        }
    });
    

    http://jsfiddle.net/jasongennaro/Y5P9k/1/

    当输入丢失focus.blur()时,检查#input的值。

    如果== ''为空,则触发警报。

    【讨论】:

      【解决方案3】:
          jQuery("#input").live('change', function() {
              // since we check more than once against the value, place it in a var.
              var inputvalue = $("#input").attr("value");
      
              // if it's value **IS NOT** ""
              if(inputvalue !== "") {
                  jQuery(this).css('outline', 'solid 1px red'); 
              }   
      
              // else if it's value **IS** ""
              else if(inputvalue === "") {
                  alert('empty'); 
              }
      
          });
      

      【讨论】:

        【解决方案4】:

        其实有一个更简单的方法可以做到这一点,只是:

        if ($("#input").is(':empty')) {
        console.log('empty');
        } else {
        console.log('not empty');
        }
        

        src:https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多