【问题标题】:Check checkbox if any of the checkboxes is checked如果选中任何复选框,请选中复选框
【发布时间】:2013-12-06 18:45:45
【问题描述】:

HTML

<label for="desktop_dimension_id">Desktop dimensions:</label>
    <span class="checkbox" id="desktopCheckboxId">
    <span class="checkbox_value">
<input id="dc1280_800" type="checkbox" name="1280x800"> 1280x800</span>                    
<span class="checkbox_value">
<input id="dc1366_768" type="checkbox" name="1366x768"> 1366x768</span>
<span class="checkbox_value">
<input id="dc1920_1080" type="checkbox" name="1920x1080"> 1920x1080</span>
</span>

    <br/>                    
 <input id="desktopCheckbox" type="checkbox" name="type[]" value="1"> Desktop

JAVASCRIPT

if(jQuery('#desktopCheckboxId input[type=checkbox]:checked').length) {
        document.getElementById('desktopCheckbox').checked = this.checked;
    }

我要检查桌面复选框是否选中了前三个复选框中的任何一个。一直在尝试几种方法,但由于未知原因似乎不起作用。那么我将如何做到这一点呢?

jsFiddle

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

    http://jsfiddle.net/pmZ7T/

    试试这个。

    $("#frmTest input[type='checkbox']").each(function(){
        if($(this).is(':checked'))
        {
            $("#desktopCheckbox").attr("checked","checked");
            return true;
        }
    });
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      $('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);
      

      但你可能是想绑定更改事件。

      $('#frmTest input[type=checkbox]').change(function() {
        $('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);
      }).change();
      

      See the demo.

      【讨论】:

      • 在这里工作正常,但在我的代码中不起作用。我正在使用jquery-1.8.0.min.js,这会是问题吗?
      【解决方案3】:

      怎么样:Demo http://jsfiddle.net/GGEFp/ *

      http://jsfiddle.net/D23eA/

      API:lengthhttp://api.jquery.com/length/

      休息应该满足需要:)

      代码

      var atLeastOne = $('#desktopCheckboxId :checkbox:checked').length > 0;
      

      【讨论】:

      • @vephelp 检查返回 false 的演示 :) jsfiddle.net/GGEFp ,您可能会错过 document.ready 也请确保它与 .change 事件以及我帖子上方的演示一样。由 xdazzz :)
      【解决方案4】:

      fiddle Demo

      var chk = $('.checkbox_value input[type=checkbox]');
      chk.change(function () {
          $('#desktopCheckbox').prop('checked', chk.filter(':checked').length > 0);
      });
      


      参考

      .change()

      .prop()

      .filter()

      【讨论】:

      【解决方案5】:

      你可以设置checked = true...

      if (jQuery('input[type=checkbox]:checked').length) {
              document.getElementById('desktopCheckbox').checked = true;
          }
      

      http://jsfiddle.net/pmZ7T/4/

      (顺便说一句,你的小提琴也在寻找一个不存在的表单ID......“frmTest”)

      【讨论】:

        猜你喜欢
        • 2014-07-11
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多