5

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

$(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/

4

2 回答 2

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');
    });
});
于 2013-09-16T11:18:26.687 回答
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]

于 2013-11-25T02:14:15.327 回答