jquery验证无法使用所选插件进行多个选择

时间:2013-09-16 10:36:13

标签: jquery jquery-validate jquery-chosen

我正在尝试根据需要使用jquery validate创建一个类型为多个的选择框,但它不起作用。这是我的代码

$(document).ready(function(){
    $('#test').chosen();
    $('#testForm').validate();
    $('#validateIt').click(function(){
        if($('#testForm').valid())
            alert('Valid');
        else
            alert('Invalid');
    });
});

HTML

<form id="testForm">
<select required style="width: 165px;" id="test" name="test" class="chzn-select multiselect" multiple="multiple">
    <optgroup label="Lab1"><option value="2">Some Program</option></optgroup>
</select>
<input type="button" id="validateIt" value="Run"/>
</form>

jsfiddle:http://jsfiddle.net/jm8Dd/

2 个答案:

答案 0 :(得分:13)

这里的问题其实很简单。 jQuery-Validator插件默认忽略隐藏的输入字段。

告诉它不要忽视隐藏的字段应该使它工作。

$(document).ready(function(){
    $('#test').chosen();
    $('#testForm').validate({ ignore: ":hidden:not(select)" });
    $('#validateIt').click(function(){   
        if($('#testForm').valid())
            alert('Valid');
        else
            alert('Invalid');
    });
});

答案 1 :(得分:0)

试试这个。它允许相互验证多个选择字段。

<form id="esq">
<select required="required" name="sqa" id="sqa">
    <option value="1" selected="selected">What was your childhood nickname?</option>
    <option value="2">In what city did you meet your spouse/significant other?</option>
    <option value="3">What is the name of your favorite childhood friend?</option>
</select>
<select required="required" name="sqb" id="sqb">
    <option value="1">What was your childhood nickname?</option>
    <option value="2" selected="selected">In what city did you meet your spouse/significant other?</option>
    <option value="3">What is the name of your favorite childhood friend?</option>
</select>
<br />
<select required="required" name="sqc" id="sqc">
    <option value="1">What was your childhood nickname?</option>
    <option value="2">In what city did you meet your spouse/significant other?</option>
    <option value="3" selected="selected">What is the name of your favorite childhood friend?</option>
</select>
<br />

$(document).ready(function () {
$.validator.addMethod("notEqualTo", function (value, element, param) {
    var pArray = param.split(",");
    var rs = true;
    $.each(pArray, function (i, v) {
        if (rs == true) {
            rs = value != $("select[name=" + v + "]").val();
        };
    });
    return rs;
}, "You must choose three separate questions.");
$("#esq").validate({
    rules: {
        sqa: {
            notEqualTo: "sqb,sqc"
        },
        sqb: {
            notEqualTo: "sqa,sqc"
        },
        sqc: {
            notEqualTo: "sqa,sqb"
        }
    }
});

});

[http://jsfiddle.net/mrmupton/F6pfB/] [1]