2

我的表单布局类似于以下:

<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.jsjquery.validate.js文件。

这里有 3 个选择选项。我只需要验证至少一个选择选项。

4

3 回答 3

0

您的 html 代码有错误。您应该将每个更改<option value=''>select option</select>为 this <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(); 
});
于 2013-05-13T08:53:10.537 回答
0
function selectValidate() {
    var check = false;
    $.each($('select'), function(index, data) {
         if (data.val() !== ''){
              check = true;
         }
    });
    return check;
}
于 2013-05-13T08:28:38.890 回答
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},
于 2013-05-13T08:35:53.863 回答