【问题标题】:jQuery Validation on checkboxes - parent and child checkboxes复选框上的 jQuery 验证 - 父复选框和子复选框
【发布时间】:2015-06-08 19:27:09
【问题描述】:

我想为复选框编写一个 jQuery 验证规则,其中必须选择父复选框类别并且也必须选择该父复选框的子类别(如果父复选框有子复选框)。否则表单将不会提交。

下面的代码有 2 个父复选框类别和第一个父复选框的 3 个子复选框类别。如果用户选择第一个父复选框,他/她必须单击一个子复选框。但是,如果他们单击没有子项的第二个父复选框,则表单可以通过。

 <ul id = "checklist">
         <li id = "box">
          <label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>

         <ul id = "checklist_children">

            <li id = "box">
          <label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
            </li>
            <li id = "box">
          <label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
            </li>
            <li id = "box">
          <label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
            </li>
         </ul>

         </li>

         <li id = "box">
          <label> <input id = "box_input" type = "checkbox"> "A CheckBox"</label>
         </li>

      </ul>

关于验证到目前为止,我写的是一个方法,它查看是否选择了任何框,如果是,则不需要验证。我要修改这个

...
 my_checkbox_rule: {
        required: function (element) {
        var boxes = $('#box_input'); 

        if (boxes.filter(':checked').length == 0) {
        return true;
        }
       },
       minlength: 1
      },
...

我想修改上面的代码以允许该功能。我可以提供比需要更多的信息。

作为额外说明,子框与父框具有相同的 id。这是故意的。

【问题讨论】:

  • 您的 input 元素必须包含 name 属性,否则 jQuery Validate 插件将不起作用。
  • 就像其他人告诉你的那样,你的id 必须是唯一的,否则你会遇到无效的 HTML 和 JavaScript 的其他问题。

标签: jquery checkbox jquery-validate


【解决方案1】:

正如其他人所说,id 选择器是唯一的,这意味着当您执行$('#box_input') 时,您只会得到第一个 id = 'box_input' 的对象。 我建议将id = 'box_input' 更改为class = 'box_input'。然后,您可以将 id 添加到第一个父级及其子级。像id = 'parent_box' 之类的东西,对于儿童来说可以是id = 'children_1' 等等,或者class = 'box_input children'。完成后我会做类似 if ($('#box_input').filter(':checked') && $('.children').filter(':checked')) { return true; }

【讨论】:

    【解决方案2】:

    据我所知 => id 属性在 HTML 中必须是唯一的,我知道这并不能解决您的问题,但它暗示(也许)您可能会遇到另一个问题...

    http://www.w3schools.com/tags/att_global_id.asp

    最佳男主。

    【讨论】:

      【解决方案3】:

      你不能用

      var boxes = $('#box_input'); 
      

      因为 id 是唯一的并且

      console.log($('#box_input').length)
      

      如果元素存在于 DOM 中,则始终为 1。

      ...但你可以使用

      var boxes = $('input[id=box_input]')
      

      (jQuery 2.1.3 托管在谷歌上)

      【讨论】:

        猜你喜欢
        • 2014-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-10
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 2018-09-28
        相关资源
        最近更新 更多