jQuery: Disable all checkboxes apart from current one

北慕城南 提交于 2020-01-23 11:09:06

问题


I have checkboxes that need to act in a similar fashion to radio button controls. Essentially when one is checked all others need to be unchecked. How can I achieve this with as little pain as possible?

So to summarise. If a checkbox is checked, all others (siblings) must then be unchecked leaving the clicked one checkstate untouched.

I already know how to uncheck all checkboxes but if I did this, I would have to first store the checked state of the checkbox that was checked, then reapply it after unchecking all checkboxes. I wondered if there was a way of doing this with some fancy jQuery selectors or some such.


回答1:


By using radio buttons. Seriously, radio buttons are there for a reason. People expect radio buttons to be a "1 out of n" selection and checkboxes to be a "0 up to n" selection.

Anyway, here's the code:

$('input:checkbox').click(function() {
    $(this).siblings('input:checkbox').removeAttr('checked');
});

Demo: http://jsfiddle.net/ThiefMaster/AVEjt/

But please, only use it if you actually need to allow the user to uncheck everything. Then it's acceptable - otherwise radio buttons are much better.




回答2:


Try this:

$(':checkbox').not( selector_for_current ).attr('checked', false);

Where selector_for_current is the "current one", often this if you're in a callback.




回答3:


Try this:

$(function() {
    $("input[type=checkbox]").click(function(){
        $(this).siblings("input[type=checkbox]:not(this)").attr("checked", "");
    });
});

See example.




回答4:


As an alternative to ThiefMaster's very good answer you could register the event on the parent form and catch all checkboxes, including those nested in a fieldset (or some other element) that would be missed using "siblings".

$("#myform").click(function(e) {
    if ($(e.target).is("input:checkbox")) {
        $("input:checkbox", this).not(e.target).removeAttr("checked");
    }
})

Demo: http://jsfiddle.net/Gs3wa/



来源:https://stackoverflow.com/questions/4935819/jquery-disable-all-checkboxes-apart-from-current-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!