JQuery: disable all checkboxes except current

I have checkboxes that should act similarly to radio button controls. Essentially, when you check, everything else should be taken off. How can I achieve this with minimal pain?

So, we summarize. If the box is checked, all the others (brothers and sisters) should then be unchecked if there is no click on one control staff.

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

+3
source share
4 answers

Using the radio buttons. Seriously, there are radio buttons for some reason. People expect the "1 of n" switches and checkboxes to be selected as "0 to n".

Anyway, here is the code:

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

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

But please use it only if you really need to allow the user to uncheck all the boxes. Then it’s acceptable - otherwise the switches are much better.

+10
source

Try the following:

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

Where selector_for_currentis the "current", often thisif you are in a callback.

+2
source

:

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

. .

0

As an alternative to ThiefMaster, a very good answer is that you can register the event in the parent form and catch all the checkboxes, including those that are nested in the set of fields (or some other element) that will be skipped using the "siblings".

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

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

0
source

Source: https://habr.com/ru/post/1790762/


All Articles