javascript - JQuery 验证 : How to check items in multiple select

标签 javascript jquery validation select

我有一个使用 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 脚本将无法处理数组中的多重选择。

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

最佳答案

当使用像 name="Europe[]" 这样的名称时,您需要使用字符串作为标识符(标识符是名称,而不是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 .

关于javascript - JQuery 验证 : How to check items in multiple select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3916669/

相关文章:

javascript - 我怎样才能在第一次点击时给 div 一个 settimeout 而不是在第二次点击时?

css - 像 <span>s inside <p>s 这样的 HTML/CSS 验证错误有多重要?

jquery - 更改日期格式验证、mvc 3 和 jQuery

javascript - 我正在尝试让表单验证与 Angular 向导一起使用

javascript - 如何以降序(反向)顺序访问javascript数组?

javascript - 谷歌开发工具时间轴 : Forced reflow is likely performance bottleneck

带有 toString 的 Javascript 嵌套函数

javascript - 将垂直滚动方向更改为水平

jQuery 用户可编辑表格单元格

javascript - jquery 类型错误 : can't assign to properties of new String