Jquery基于选择文本的条件validation

我想仅在“select1”字段中选定的文本是“其他”时才需要“其他”字段我正在尝试的规则是: other: { required: function(element){ return $("#select1 option:selected").text() == "Other"; } } 我做错了什么? 这是代码:

       $(document).ready(function(){ $('form:first').validate({ rules: { cname: { required: true, }, select1: { valueNotEquals: "0" } }, other: { required: function(element){ return $("#select1 option:selected").text() == "Other"; } }, messages: { cname: "Please enter a valid naaaammmeeee.", select1: "Please choose a valid option", other: "Please enter a valid other value", }, }); $.validator.addMethod("valueNotEquals", function(value, element, arg){ return arg != value; }, "Value must not equal arg."); });    
A simple comment form with submit validation and default messages

*

Please choose a value 1 2 Other

*

有许多问题主要与JSON格式有关:

  1. 这里有一个额外的closing bracket

     select1: { valueNotEquals: "0" } }, 
  2. rules定义的末尾和messages定义开始之前缺少一个closing bracket

    return $(“#select1 option:selected”)。text()==“Other”; }, }
    消息:{

  3. 每个选项末尾的额外comma是不必要的

  4. validate.js路径中的空格(这可能是问题中的一个拼写错误)

    这是更正后的代码:

     

更新答案在这里找到一个小提琴的演示: http : //jsfiddle.net/3jrTM/

 $('form:first').validate({ rules: { cname: { required: true }, select1: { valueNotEquals: "0" }, other: { required: function(element) { return $("#select1 option:selected").text() == "Other"; } }, }, messages: { cname: "Please enter a valid naaaammmeeee.", select1: "Please choose a valid option", other: "Please enter a valid other value" } }); $.validator.addMethod("valueNotEquals", function(value, element, arg) { return arg != value; }, "Value must not equal arg.");​ 

您可以删除包含“0”的选项的值。

  

当一个选项不包含值atrribute时,jQuery validate将其处理为空或未给出。

  

您可以将“required”作为类添加到selectbox中,以便jQuery validate将提示“必需”警告。

 $('select').change(function() { var text = $('select option:selected').text();​​​​​​​​​ if(text == 'Other') { $('input[name=other]').attr('disabled', false); } }); 

这就是你的意思