首页 文章

使用jQuery检查输入是否为空

提问于
浏览
442

我有一个表格,我希望所有字段都填写 . 如果一个字段被点击,然后没有填写,我想显示一个红色背景 .

这是我的代码:

$('#apply-form input').blur(function () {
  if ($('input:text').is(":empty")) {
    $(this).parents('p').addClass('warning');
  }
});

无论填写的字段是否填写,它都会应用警告类 .

我究竟做错了什么?

16 回答

  • 142

    你也可以用..

    $('#apply-form input').blur(function()
    {
        if( $(this).val() == '' ) {
              $(this).parents('p').addClass('warning');
        }
    });
    

    如果您对空间有疑问,请尝试..

    $('#apply-form input').blur(function()
    {
        if( $(this).val().trim() == '' ) {
              $(this).parents('p').addClass('warning');
        }
    });
    
  • 8

    怎么没有人提到

    $(this).filter('[value=]').addClass('warning');
    

    对我来说似乎更像jquery

  • 678
    $('#apply-form input').blur(function()
    {
        if( !$(this).val() ) {
              $(this).parents('p').addClass('warning');
        }
    });
    

    并且您不一定需要 .length 或查看它是否是 >0 ,因为无论如何空字符串的计算结果为false,但是如果您想要出于可读性的目的:

    $('#apply-form input').blur(function()
    {
        if( $(this).val().length === 0 ) {
            $(this).parents('p').addClass('warning');
        }
    });
    

    如果您确定它将始终在textfield元素上运行,那么您可以使用 this.value .

    $('#apply-form input').blur(function()
    {
          if( !this.value ) {
                $(this).parents('p').addClass('warning');
          }
    });
    

    另外,您应该注意 $('input:text') 抓取多个元素,指定上下文或使用 this 关键字,如果您只想引用一个单独的元素(在那里提供's one textfield in the context' s后代/子元素) .

  • 2

    每个人都有正确的想法,但我喜欢更明确一些,并削减 Value 观 .

    $('#apply-form input').blur(function() {
         if(!$.trim(this.value).length) { // zero-length string AFTER a trim
                $(this).parents('p').addClass('warning');
         }
    });
    

    如果你不使用.length,那么一个'0'的条目可以被标记为坏,并且一个5个空格的条目可以在没有$ .trim的情况下标记为ok . 最好的运气 .

  • 0

    在模糊上做这件事太有限了 . 它假设有关注表单字段,所以我更喜欢在提交时进行,并通过输入进行映射 . 经过多年处理花哨的模糊,专注等技巧,让事情变得更简单会产生更多的可用性 .

    $('#signupform').submit(function() {
        var errors = 0;
        $("#signupform :input").map(function(){
             if( !$(this).val() ) {
                  $(this).parents('td').addClass('warning');
                  errors++;
            } else if ($(this).val()) {
                  $(this).parents('td').removeClass('warning');
            }   
        });
        if(errors > 0){
            $('#errorwarn').text("All fields are required");
            return false;
        }
        // do the ajax..    
    });
    
  • 1
    if ($('input:text').val().length == 0) {
          $(this).parents('p').addClass('warning');
    }
    
  • 2

    keyup事件将检测用户是否也清除了该框(即退格引发事件,但退格不会引发IE中的按键事件)

    $("#inputname").keyup(function() {
    
    if (!this.value) {
        alert('The box is empty');
    }});
    
  • 0

    请考虑使用the jQuery validation plugin . 对于简单的必填字段来说,这可能有些过分,但它已经足够成熟,它可以处理你甚至还没有想过的边缘情况(在我们遇到它们之前也不会有任何人) .

    您可以使用“required”类标记必填字段,在$(document).ready()中运行$('form') . validate(),这就是所需要的 .

    它甚至也托管在Microsoft CDN上,以便快速交付:http://www.asp.net/ajaxlibrary/CDN.ashx

  • 18

    :empty 伪选择器用于查看元素是否不包含子元素,您应该检查值:

    $('#apply-form input').blur(function() {
         if(!this.value) { // zero-length string
                $(this).parents('p').addClass('warning');
         }
    });
    
  • 3

    还有一件事你可能想要考虑,目前它只能添加警告类,如果它是空的,当表单不再为空时如何再次删除类 .

    像这样:

    $('#apply-form input').blur(function()
    {
        if( !$(this).val() ) {
              $(this).parents('p').addClass('warning');
        } else if ($(this).val()) {
              $(this).parents('p').removeClass('warning');
        }
    });
    
  • 5
    function checkForm() {
      return $('input[type=text]').filter(function () {
        return $(this).val().length === 0;
      }).length;
    }
    
  • 11

    以下是使用所选输入的keyup的示例 . 它还使用修剪来确保一系列只有空白字符的字符不会触发真实的响应 . 这是一个可用于开始搜索框或与该类型功能相关的内容的示例 .

    YourObjNameSpace.yourJqueryInputElement.keyup(function (e){
       if($.trim($(this).val())){
           // trimmed value is truthy meaning real characters are entered
        }else{
           // trimmed value is falsey meaning empty input excluding just whitespace characters
        }
    }
    
  • 3
    $(function() {
      var fields = $('#search_form').serializeArray();
      is_blank = true;
      for (var i = 0; i < fields.length; i++) {
        // excluded fields
        if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
          if (fields[i].value) {
            is_blank = false;
          }
        }
      }
      if (is_blank) {
        $('#filters-button').append(': OFF');
      }
      else {
        $('#filters-button').append(': ON');
      }
    });
    

    检查所有字段是否为空,并在Filter_button上追加ON或OFF

  • 4

    你可以尝试这样的事情:

    $('#apply-form input[value!=""]').blur(function() {
        $(this).parents('p').addClass('warning');
    });
    

    它仅将 .blur() 事件应用于具有空值的输入 .

  • 3
    <script type="text/javascript">
    $('input:text, input:password, textarea').blur(function()
        {
              var check = $(this).val();
              if(check == '')
              {
                    $(this).parent().addClass('ym-error');
              }
              else
              {
                    $(this).parent().removeClass('ym-error');  
              }
        });
     </script>// :)
    
  • 30

    使用HTML 5,我们可以使用“必需”的新功能,只需将其添加到您想要的标记中,如:

    <input type='text' required>

相关问题