使用jQuery检查具有特定类的所有输入是否为空 [英] Check if all inputs with a certain class are empty using jQuery

查看:105
本文介绍了使用jQuery检查具有特定类的所有输入是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查具有特定类的所有输入字段是否为空. 现在,我有以下代码:

I'm trying to check if all input fields with a certain class are empty. Right now I have the following code:

HTML

<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>

jQuery

$('.check-fields').on('click', function () {

  var value = $('.required-entry').filter(function () {
    return this.value != '';
  });

  if (value.length == 0) {
    alert('Please fill out all required fields.');
  } else if (value.length > 0) {
    alert('Everything has a value.');
  }
});

但是,这引发了一条信息:一切都有价值".如果任何一个输入具有值.我只想在此类的每个输入中都包含某些内容时才抛出该消息.

But this throws the message "Everything has a value." if ANY one of the inputs has a value. I'm trying to only throw that message when every input with this class has something in it.

$('.check-fields').on('click', function () {

    var value = $('.required-entry').filter(function () {
        return this.value != '';
    });

    if (value.length == 0) {
        console.log('Please fill out all required fields.');
    } else if (value.length > 0) {
        console.log('Everything has a value.');
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>

我也用一些稍有不同的代码来摆弄小提琴..当第一个输入是唯一填充的内容时,还会引发一切都有值"消息.

I also have this fiddle with slightly different code.. also throws the Everything has a value message when the first input is the only one filled.

$('.check-fields').on('click', function () {
    
    if($.trim($('.required-entry').val()) === '') {
        console.log('Please fill out all required fields.');
    } else {
        console.log('Everything has a value.');
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<input type="text" class="required-entry">
<button class="check-fields">Check Fields</button>

推荐答案

检查以下代码:

$('.check-fields').on('click', function () {

    var reqlength = $('.required-entry').length;
    console.log(reqlength);
    var value = $('.required-entry').filter(function () {
        return this.value != '';
    });

    if (value.length>=0 && (value.length !== reqlength)) {
        alert('Please fill out all required fields.');
    } else {
        alert('Everything has a value.');
    }
});

这篇关于使用jQuery检查具有特定类的所有输入是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆