2013-12-16 49 views
0

我试图使用jQuery validation plugin验证我的应用程序中有一个表单。jQuery根据复选框验证不同的字段

形式(简体)情况如下:

<form id="my_form" action="#" method="post" novalidate="novalidate"> 
    <input id="my_hidden_input" type="text" style="display:none;"> 
    <input id="my_select_checkbox" class="checkbox" type="checkbox" value="1"> 
    <select id="my_select_1" class="select valid" type="select"> 
    <select id="my_select_2" class="select valid" type="select"> 
</form> 

我想要做的就是验证如下:如果复选框被选中,我检查出一个值在我的第一选择选择,如果复选框未被选中,我检查我的第二个列表的选定值。

我想是这样的:

$('#my_form').validate({ // initialize the plugin 
    rules: { 
     my_hidden_input:{ 
      "checkboxSelect": true, 
     }, 
    }, 
    submitHandler: function (form) { // for demo 
     console.log($("#monitors_start").value); 
     return false; 
    } 
}); 


jQuery.validator.addMethod(
    "checkboxSelect", 
    function() { 
     if ($("#my_select_checkbox").attr('checked')) 
      return $("#my_select_1").val(); 
     else 
     return $("#my_select_2").val(); 
    }, "test addMethod" 
); 

但似乎我没有得到它正确的......如果有人可以帮助它会不胜感激!

谢谢!

+1

是您的函数被调用? – CSL

+1

像http://jsfiddle.net/arunpjohny/7Kscj/8/ –

+0

@ CSL好吧,我想'console.log'之前的东西返回,但没有打印出来 –

回答

2

可以使用取决于像

选项
var validator = $('#form').validate({ 
    rules: { 
     my_select_1: { 
      required: { 
       depends: function() { 
        return $('#my_select_checkbox').is(':checked') 
       } 
      } 
     }, 
     my_select_2: { 
      required: { 
       depends: function() { 
        return !$('#my_select_checkbox').is(':checked') 
       } 
      } 
     } 
    }, 
    messages: {} 
}); 

演示:Fiddle

+0

完美!谢谢 –