简体   繁体   中英

Allow only one selection per column and row in a webpage's grid of radio buttons

I have a grid of 5x5 radio buttons, with the each row being a "group" (sharing the same name).

I want to make it so that when A3 is selected, B3 C3 D3 and E3 can not be selected and for example if B4 is selected no other button in row B or column 4 can be selected.

I have tried using multiple names, but as far as my testing goes this doesn't work. I have tried to find a solution with Jquery but nothing seems to work. Is the only way to achieve this using a bit of complex JavaScript?

This is easiest done by adding classes to each radio button, one for column and one for row. As a radio button is checked, all that needs to be done is to disable those with one matching class (ie matching row or column).

$('input[type="radio"]').change(function() {
    var classes = $(this).prop('class').split(' ');
    for (i in classes)
        $('.'+classes[i]).attr('disabled', true);
});

A JSFiddle that demonstrates the technique.

Rows are handled automatically if they have the same name. Disabling other radio-buttons prevents you from changing your mind. I'd consider deselcting conflicting Radiobuttons.

$(".radiobutton").on("change", function(ev) {
    var clicked = $(ev.target);
    $(".radiobutton[data-col=" + clicked.data("col") + "]").attr("checked", false);
    clicked.attr("checked", true);
});

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM