打开/关闭复选框

时间:2010-11-14 10:51:51

标签: jquery checkbox jquery-selectors toggle

我有以下内容:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

我希望点击id="select-all-teammembers"在已选中和未选中之间切换。想法?这不是几十行代码?

23 个答案:

答案 0 :(得分:677)

你可以写:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

在jQuery 1.6之前,当我们只有attr()而不是prop()时,我们曾写过:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

但是prop()在应用于“布尔”HTML属性时具有比attr()更好的语义,因此在这种情况下通常是首选。

答案 1 :(得分:197)

//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 

答案 2 :(得分:58)

我知道这已经过时了,但问题有点模棱两可,因为切换可能意味着每个复选框都应切换其状态,无论是什么。如果您有3个已选中且2未选中,则切换将使前3个未选中,最后2个选中。

为此,这里的解决方案都不起作用,因为它们使所有复选框具有相同的状态,而不是切换每个复选框的状态。在许多复选框上执行$(':checkbox').prop('checked')会返回所有.checked二进制属性之间的逻辑AND,即如果未选中其中一个,则返回的值为false

如果您想实际切换每个复选框状态而不是使它们全部相等,则需要使用.each(),例如。

   $(':checkbox').each(function () { this.checked = !this.checked; });

请注意,处理程序中不需要$(this),因为.checked属性存在于所有浏览器中。

答案 3 :(得分:16)

这是你想要的另一种方式。

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});

答案 4 :(得分:9)

我认为触发点击更简单:

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 

答案 5 :(得分:8)

从jQuery 1.6开始,您可以使用.prop(function)来切换每个找到元素的已检查状态:

$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});

答案 6 :(得分:7)

使用此插件:

$.fn.toggleCheck  =function() {
       if(this.tagName === 'INPUT') {
           $(this).prop('checked', !($(this).is(':checked')));
       }

   }

然后

$('#myCheckBox').toggleCheck();

答案 7 :(得分:6)

我能想到的最佳方式。

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});

$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   

<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}

答案 8 :(得分:2)

在特定条件下,Check-all复选框应更新本身。尝试点击'#select-all-teammembers'然后取消勾选几项,然后再次点击全选。你可以看到不一致。为了防止它使用以下技巧:

  var checkBoxes = $('input[name=recipients\\[\\]]');
  $('#select-all-teammembers').click(function() {
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    $(this).prop("checked", checkBoxes.is(':checked'));
  }); 

BTW所有复选框DOM对象应该如上所述进行缓存。

答案 9 :(得分:2)

这是一种jQuery切换复选框的方法,无需选中html5&amp;复选框。标签:

package sysout;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class DisableSysout {

    private static PrintStream outOriginal;

    public static void main(String[] args) {
      outOriginal = System.out;
      doSysout();
      disableSysout();
      doSysout();
    }

    private static void doSysout() {
      long start = System.currentTimeMillis();
      for (int i=0;i<=500000;i++){
          System.out.println("Mess " + i);     
          System.out.println(i);
       }
      long end = System.currentTimeMillis();

      enableSysout();
      System.out.println("time="+ (end-start));
    }


    private static void enableSysout() {
      System.setOut(outOriginal);
    }

    private static void disableSysout() {

      System.setOut(new PrintStream(new OutputStream() {

        @Override
        public void write(int b) throws IOException {
        }

      }));
    }
}

http://www.bootply.com/A4h6kAPshx

答案 10 :(得分:2)

假设这是一个必须切换复选框的图像,这对我有用

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">

答案 11 :(得分:1)

jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

答案 12 :(得分:1)

你也可以这样写

$(function() {
    $("#checkbox-toggle").click(function() {
        $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
    });
});

当用户点击带有ID&#39;#checkbox-toggle&#39;的按钮时,只需要调用复选框的点击事件。

答案 13 :(得分:1)

更好的方法和用户体验

$('.checkall').on('click', function() {
   var $checks  = $('checks');
   var $ckall = $(this);

    $.each($checks, function(){
        $(this).prop("checked", $ckall.prop('checked'));
    });
});

$('checks').on('click', function(e){
   $('.checkall').prop('checked', false);
});

答案 14 :(得分:1)

<table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
<thead>
    <tr>
        <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
        <th class="col-xs-2">#ID</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox" name="order333"/></td>
        <td>{{ order.id }}</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="order334"/></td>
        <td>{{ order.id }}</td>
    </tr>
</tbody>                  
</table>

尝试:

$(".table-datatable .select_all").on('click', function () {
    $("input[name^='order']").prop('checked', function (i, val) {
        return !val;
    });
});

答案 15 :(得分:1)

最基本的例子是:

// get DOM elements
var checkbox = document.querySelector('input'),
    button = document.querySelector('button');

// bind "cilck" event on the button
button.addEventListener('click', toggleCheckbox);

// when clicking the button, toggle the checkbox
function toggleCheckbox(){
  checkbox.checked = !checkbox.checked;
};
<input type="checkbox">
<button>Toggle checkbox</button>

答案 16 :(得分:1)

只需使用此

即可
$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});

答案 17 :(得分:0)

在我的猜测中,建议正常变体的最正确的人是GigolNet Gigolashvili,但我想建议更美丽的变体。检查

$(document).on('click', '.fieldWrapper > label', function(event) {
    event.preventDefault()
    var n = $( event.target ).parent().find('input:checked').length
    var m = $( event.target ).parent().find('input').length
    x = n==m? false:true
    $( event.target ).parent().find('input').each(function (ind, el) {
        // $(el).attr('checked', 'checked');
        this.checked = x
    })
})

答案 18 :(得分:0)

分别设置'checked'或null而不是true或false将完成工作。

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');

答案 19 :(得分:0)

如果你想单独切换每个方框(或者只有一个方框也可以工作):

我建议使用.each(),因为如果您想要发生不同的事情,它很容易修改,并且仍然相对简短易读。

e.g。 :

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});

旁注... 不确定为什么每个人都使用.attr()或.prop()来(un)检查事物。

据我所知,element.checked在所有浏览器中的效果都一样吗?

答案 20 :(得分:0)

这个对我有用。

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });

答案 21 :(得分:0)

此代码将在单击Web模板中使用的任何切换开关动画时切换复选框。替换&#34; .onoffswitch-label&#34;在您的代码中可用。 &#34; checkboxID&#34;是在这里切换的复选框。

$('.onoffswitch-label').click(function () {
if ($('#checkboxID').prop('checked')) 
 {
   $('#checkboxID').prop('checked', false);
 }
else 
 {
   $('#checkboxID').prop('checked', true);
 }
});

答案 22 :(得分:-3)

那么有一种更简单的方法

首先给您的复选框一个类示例'id_chk'

然后在复选框内将控制'id_chk'复选框状态put:

<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />

多数民众赞成,希望这会有所帮助

相关问题