我的表单布局类似于以下内容:
<form action='' method="post" id='myform'>
<select name='select1'>
<option value=''>select option</select>
<option value='a'> a </option>
<option value='b'> b </option>
<option value='c'> c </option>
</select>
<select name='select2'>
<option value=''>select option</select>
<option value='e'> e </option>
<option value='f'> f </option>
<option value='g'> g </option>
</select>
<select name='select3'>
<option value=''>select option</select>
<option value='h'> h </option>
<option value='i'> i </option>
<option value='j'> j </option>
</select>
</form>
<script> $('#myform').validate(); </script>
注意:我已添加jquery.js
和jquery.validate.js
个文件。
这里有3个选择选项。我只需要验证至少一个选择选项。
答案 0 :(得分:0)
function selectValidate() {
var check = false;
$.each($('select'), function(index, data) {
if (data.val() !== ''){
check = true;
}
});
return check;
}
答案 1 :(得分:0)
创建自己的验证方法:
$.validator.addMethod("selectNone", function(value, element) {if (element.value == " ") {return false;} else {return true};} ),
然后添加规则:
yourSelectID1: {required:true, selectNone:true},
yourSelectID2: {required:true, selectNone:true},
yourSelectID3: {required:true, selectNone:true},
答案 2 :(得分:0)
你的html代码有误。您应该将每个<option value=''>select option</select>
更改为此<option value=''>select option</option>
。所以你的HTML将是这样的:(我添加了提交按钮以显示功能)
的 jsFiddle Live Demo 强>
的 HTML 强>
<form action='' method="post" id='myform' >
<select name='select1' >
<option value=''>select option</option>
<option value='a'> a </option>
<option value='b'> b </option>
<option value='c'> c </option>
</select>
<select name='select2' >
<option value=''>select option</option>
<option value='e'> e </option>
<option value='f'> f </option>
<option value='g'> g </option>
</select>
<select name='select3' >
<option value=''>select option</option>
<option value='h'> h </option>
<option value='i'> i </option>
<option value='j'> j </option>
</select>
<input type='submit' value='validate '>
</form>
主要功能是validateSelects()
的 JS 强>
function validateSelects()
{
var m = false;
$.each($('select'),function()
{
if( $(this).val() != ''){ m=true; }
});
return(m);
}
// For the functionality.
$('#myform').on('submit',function()
{
return validateSelects();
});