jQuery - 查找具有没有值的给定类的任何输入 [英] jQuery - Find any input with a given class that has no value
问题描述
我有一个(非常)基本的验证脚本。我基本上想检查类.required的任何输入,看看是否有值a)空白或b)0如果是,则在我的表单提交上返回false。此代码似乎没有返回false:
I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
将此函数附加到我的表单的onSubmit处理程序是没有返回任何结果。任何关于此事的光明都将受到赞赏。
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
我基本上在使用类.required迭代所有输入的函数之后,如果ANY有空值或0值,则在我的提交时返回false并更改背景所有表现不佳的输入颜色为橙色。
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
推荐答案
您的代码目前获得第一个 的jquery.com/val/\"rel =noreferrer>
.required ,来自 .val()
.val()
文档:
Your code currently gets the .val()
for the first .required
, from the .val()
documentation:
获取匹配元素集中第一个元素的当前值。
Get the current value of the first element in the set of matched elements.
您需要逐个过滤每个元素,像这样:
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
或更紧凑的版本:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
这篇关于jQuery - 查找具有没有值的给定类的任何输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!