【问题标题】:JQuery validation : How to check items in multiple selectJQuery验证:如何检查多项选择
【发布时间】:2010-10-12 16:02:31
【问题描述】:

我有一个使用 JQuery 验证插件的表单。

<label>
    <input name="Distribution[]" type="checkbox" id="dist_europe" class="required minlength:1" value="Europe" />  Europe 
</label>

<select name="Europe[]" size="5" multiple id="Europe">
   <option value='Albania'>Albania</option>
   <option value='Andorra'>Andorra</option>
   <option value='Austria'>Austria</option>
</select>

我需要进行“条件”验证。 例如。如果选中复选框,请确保“选择选项被选中”中至少有一项。

 $(document).ready(function(){
     $("#commentForm").validate({
      rules: {
              Europe: {
                required: "#dist_europe:checked",
                minlength: 1
              }  
      },
      messages: {
        Europe: "Please select at least 1 country"
      }
     }
})

我现在面临的问题是:

  1. 我能够检测到复选框被选中。
  2. 但是,我无法检查“选择”数组 Europe[]
  3. 如果我删除数组并将其命名为 Europe,我将能够检测到至少选择了一项。但是,这样做意味着后端 PHP 脚本将无法处理数组中的多选。

我该如何解决这个问题?谢谢

【问题讨论】:

    标签: javascript jquery validation select


    【解决方案1】:

    当使用像name="Europe[]" 这样的名称时,您需要使用字符串作为标识符(标识符是name,而不是元素的id ) 在rulesmessages 中,像这样:

    $(document).ready(function(){
         $("#commentForm").validate({
          rules: {
            'Europe[]': {
                    required: "#dist_europe:checked",
                    minlength: 1
                  }  
          },
          messages: {
            'Europe[]': "Please select at least 1 country"
          },
         debug: true
        });
    });
    

    You can test it out here.

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2013-03-17
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多