我有一些动态的选择元素。提交表单时,我想检查是否还有其中任何一个尚未被选中,即value == ""
,如果是这样就抛出一个错误,任何想法如何在Jquery中这样做?谢谢!
<div class="container-seller-commission">
<div class="row-seller-commission">
<select name="seller" id="seller" class="select-seller valid">
<option value=""></option>
<option value="4" selected="selected">Agent</option>
<option value="2">Crisalix Global</option>
<option value="1">Owner</option>
<option value="3">Support</option>
</select>
</div>
</div>
<div class="row-seller-commission">
<select name="seller" id="seller" class="select-seller valid">
<option value=""></option>
<option value="4" disabled="disabled">Agent</option>
<option value="2" selected="selected">Crisalix Global</option>
<option value="1">Owner</option>
<option value="3">Support</option>
</select>
</div>
<div class="row-seller-commission">
<select name="seller" id="seller" class="select-seller valid">
<option value=""></option>
<option value="4" disabled="disabled">Agent</option>
<option value="2">Crisalix Global</option>
<option value="1" selected="selected">Owner</option>
<option value="3" disabled="disabled">Support</option>
</select>
</div>
答案 0 :(得分:2)
<强> Here is the working fiddle 强>
以下是小提琴中使用的代码,
$(document).ready(function(){
$("#validateButtonId").on("click",function(){
var selectBoxFlag = true;
//iterating through all the select boxes with class 'select-seller'
$(".select-seller").each(function(){
if($(this).val() == ""){
selectBoxFlag = false;
}
});
if(selectBoxFlag){
$("#formId").submit();
}else{
alert("Selectbox value is not selected!");
}
});
});
“validateButtonId”是您在尝试提交表单时使用的按钮的ID,请注意,此按钮的input type
应为button
而不是{{1} }
答案 1 :(得分:0)
使用$('.select-seller')
选择所有选择框,然后使用jquery-function each()
循环遍历所有框。在循环内部,您可以使用$(this).val()
获取值,并将其与空字符串进行比较。然后你要做的就是跟踪至少一个盒子是否缺少选择:
$(document).ready(function(){
var unselected = false;
$('.select-seller').each(function() {
if ($(this).val() === '') {
unselected = true;
}
});
if (unselected) {
//Atleast one box is missing a selection
} else {
//All boxes has a selection
}
});
答案 2 :(得分:0)
<强> Working fiddle 强>
在提交时选中所有选择:
$('form').submit(function(e){
e.preventDefault();
var empty_select = false;
$('select').each(function(){
if($(this).val()==''){
empty_select = true
}
})
if(empty_select)
alert('Fill all selects')
else
alert('submit')
})