make checkbox behave like radio buttons with javascript

前端 未结 11 754
迷失自我
迷失自我 2020-11-28 06:28

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previ

11条回答
  •  悲哀的现实
    2020-11-28 07:17

    You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:

    function clickReset ()
    {
        var isChecked = false,
            clicked = $(this),
            set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
    
        if (isChecked = clicked.attr ('checked'))
        {
            set.attr ('checked', false);
        }
        return true;
    }
    
    $(function ()
    {
        $('.test').click (clickReset);
    });
    

    Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.

    I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.

    EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.

    http://jsfiddle.net/j53gd/1/

提交回复
热议问题