【问题标题】:Counting checkboxes of element计算元素的复选框
【发布时间】:2015-08-14 23:47:49
【问题描述】:

好的,所以我有一些 javascript 代码旨在做两件事:勾选具有相同值的复选框(如果选中值为“3”的复选框,则还应选中任何其他值为“3”的复选框)。这也意味着计算之后总共有多少个复选框。这完美无缺。

  $(".chkbox").on('change',function() {
                    var max_number =8;                  

                    var val = ($(this).val();
                    if ($(this).is(":checked")) {

                      $(":checkbox[value='" + val + "']").prop("checked", true);
                    } else {
                      $(":checkbox[value='" + val + "']").prop("checked", false);
                    }
                    var count = $("[type='checkbox']:checked").length;
                    if (count>=max_number){
                        alert("too many chosen!");
                    }
                    alert (count);
                  });

但是,html 中有一些不相关的复选框,并且被错误地计数。因此,我为包含相关复选框的部分提供了“test”的 id 并重写了 javascript:

 $(".chkbox").on('change', function() {
   var max_number = 8;

   var val = ($(this).children("#test")).val();
   if (($(this).children("#test")).is(":checked")) {

     $(":checkbox[value='" + val + "']").prop("checked", true);
   } else {
     $(":checkbox[value='" + val + "']").prop("checked", false);
   }
   var count = $("[type='checkbox']:checked").length;
   if (count >= max_number) {
     alert("too many chosen!");
   }
   alert(count);
 });
<section id="test">
  <table style="display:inline-block;" border="1">
    <tr id="9">
      <td>9</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="10">
      <td>10</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
      </td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" /><a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
      </td>
    </tr>
    <tr id="11">
      <td>11</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <tr id="12">
      <td>12</td>
      <td style="background-color:#">
        <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" /><a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
      </td>
      <td>&nbsp;</td>
    </tr>
    <td>18</td>
    <td style="background-color:#">
      <input type="checkbox" class="chkbox" name="selection[array_name][]" title="2" value="2" /><a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
    </td>
    <td>&nbsp;</td>
    </tr>
  </table>
</section>

这会正确计算复选框的数量 - 但它不再勾选测试中具有相同值的所有复选框!我该如何解决这个问题?

【问题讨论】:

  • 你也可以分享你的 HTML 吗?
  • @VimalanJayaGanesh 完成...我不得不减少它(实际上是几百行),但应该准确反映整体代码

标签: javascript jquery checkbox


【解决方案1】:

在您的 JS 的第 3 行,您正在调用

var val = ($(this).children("test")).val();

首先,您不能只使用 ("test"),因为它不是有效的选择器(您缺少“#”)。

此外,$(this) 指的是更改后的输入元素,在您的情况下是一个复选框,它没有子元素。

所以,如果你想要复选框的值,你肯定要在 $(this) 上调用 .val():

var val = $(this).val();

如果您只想定位具有“测试”ID 的复选框,您可以在设置事件时这样做:

$("#test .chkbox").on('change'....

.children() 将遍历 DOM,寻找与选择器匹配的元素。如果你想遍历 DOM,我想你可以使用 .closest()。然后,您将检查目标元素是否具有 ID 为#test 的父元素,然后执行您的操作:

if ($(this).closest("#test").length > 0) {
    var val = $(this).val();
    // other stuff...
}

【讨论】:

    【解决方案2】:

    我建议:

    // binding the anonymous function of the on() method as the
    // event-handler of the <input> elements of type=checkbox, and
    // class of 'chkbox':
    $('input[type=checkbox].chkbox').on('change', function() {
      var maxNumber = 8,
    
          // caching a reference to the changed element:
          changed = this,
    
          // caching a reference to the changed element's value:
          value = changed.value,
    
          // caching the collection of relevant checkboxes:
          checkboxes = $('input[type=checkbox].chkbox');
    
      // updating the checked property of each of the checkboxes:
      checkboxes.prop('checked', function () {
    
        // returning true (and therefore setting the
        // checked property to true) if the current
        // <input> element's value is equal to the value
        // of the changed <input> AND if the changed element
        // is checked (thereby allowing us to uncheck the
        // checkboxes); if the assessment evaluates to false
        // the checked property is set to false:
        return this.value === value && changed.checked;
      });
    
      // setting the text of the '#result' element - adjust
      // to taste, but I wasn't sure where you wanted the
      // relevant number to be shown:
      $('#result').text(function () {
    
        // here we filter the checkboxes collection to only
        // those that are checked (using the CSS ':checked'
        // selector:
        return checkboxes.filter(':checked').length + ' of ' + checkboxes.length + ' checkboxes checked';
      });
    
    }).change();
    

    $('input[type=checkbox].chkbox').on('change', function() {
      var maxNumber = 8,
        changed = this,
        value = changed.value,
        checkboxes = $('input[type=checkbox].chkbox');
    
      checkboxes.prop('checked', function() {
        return this.value === value && changed.checked;
      });
    
      $('#result').text(function() {
        return checkboxes.filter(':checked').length + ' of ' + checkboxes.length + ' checkboxes checked';
      });
    
    }).change();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <section id="test">
      <table style="display:inline-block;" border="1">
        <tr id="9">
          <td>9</td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" />
            <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
          </td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" />
            <a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
          </td>
        </tr>
        <tr id="10">
          <td>10</td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="1" value="1" />
            <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
          </td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="5" value="5" />
            <a href="http://www.example.com/array_name/VARIABLE20110" target="_blank">VARIABLE20110</a>
          </td>
        </tr>
        <tr id="11">
          <td>11</td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" />
            <a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
          </td>
          <td>&nbsp;</td>
        </tr>
        <tr id="12">
          <td>12</td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="6" value="6" />
            <a href="http://www.example.com/array_name/VARIABLE20070" target="_blank">VARIABLE20070</a>
          </td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td>18</td>
          <td style="background-color:#">
            <input type="checkbox" class="chkbox" name="selection[array_name][]" title="2" value="2" />
            <a href="http://www.example.com/array_name/VARIABLE10010" target="_blank">VARIABLE10010</a>
          </td>
          <td>&nbsp;</td>
        </tr>
      </table>
    </section>
    <div id="result"></div>

    参考资料:

    【讨论】:

    • 很好地重写了匿名函数 - 但我很困惑:这如何防止选择/计数不相关的复选框(即那些不是“测试”的子项)?
    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2014-10-10
    • 2012-06-10
    • 2012-01-20
    相关资源
    最近更新 更多