gpt4 book ai didi

jquery - 使用 jQuery 检查特定类的所有输入是否为空

转载 作者:行者123 更新时间:2023-12-01 00:35:13 24 4
gpt4 key购买 nike

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

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.');
}
});

但这会抛出消息“一切都有值(value)”。如果任何一个输入有值。我试图仅在此类的每个输入都包含某些内容时才抛出该消息。

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

我也有这个 fiddle ,其代码略有不同。当第一个输入是唯一填充的输入时,也会抛出“一切都有值”消息。

$('.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 - 使用 jQuery 检查特定类的所有输入是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31923968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com