使用jQuery检查输入是否为空

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

这是我的代码:

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

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

我究竟做错了什么?


#1楼

<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>// :)

#2楼

怎么没有人提到

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

对我来说似乎更像jquery


#3楼

$('#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关键字,如果您只想引用一个单独的元素(假设在上下文的后代/子元素中有一个文本字段)。


#4楼

if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}

#5楼

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

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

#6楼

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

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

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


#7楼

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

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

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


#8楼

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

<input type='text' required>


#9楼

以下是使用所选输入的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
    }
}

#10楼

$(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


#11楼

 function checkForm() { return $('input[type=text]').filter(function () { return $(this).val().length === 0; }).length; } 


#12楼

你也可以用..

$('#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');
    }
});

#13楼

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

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});

#14楼

你可以尝试这样的事情:

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

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


#15楼

很棒的答案集,想补充说你也可以使用:placeholder-shown CSS选择器。 使用IMO要小一些,特别是如果你已经使用了jQ并且在输入上有占位符。

 if ($('input#cust-descrip').is(':placeholder-shown')) { console.log('Empty'); } $('input#cust-descrip').on('blur', '', function(ev) { if (!$('input#cust-descrip').is(':placeholder-shown')) { console.log('Has Text!'); } else { console.log('Empty!'); } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description"> 

如果您有必要的输入,也可以使用:valid:invalid选择器。 如果在输入上使用必需属性,则可以使用这些选择器。


#16楼

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

像这样:

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

#17楼

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

$('#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..    
});
发布了0 篇原创文章 · 获赞 2 · 访问量 5920

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104063096