jQuery check/uncheck radio button onclick

前端 未结 24 2773
滥情空心
滥情空心 2020-12-01 05:23

I have this code to check/uncheck a radio button onclick.

I know it is not good for the UI, but I need this.

$(\'#radioinstant\').click(function() {          


        
24条回答
  •  感动是毒
    2020-12-01 05:41

    I believe this is the problem: If you have more than one radio button, and one of them is clicked, there is no way to deselect all of them. What is needed is a "none or only one" selector, so checkboxes would not be appropriate. You could have a "clear" button or something like that to deselect all, but it would be nice to just click the selected radio button to deselect it and go back to the "none" state, so you don't clutter your UI with an extra control.

    The problem with using a click handler is that by the time it is called, the radio button is already checked. You don't know if this is the initial click or a second click on an already checked radio button. So I'm using two event handlers, mousedown to set the previous state, then the click handler as used above:

    $("input[name=myRadioGroup]").mousedown(function () 
    {
        $(this).attr('previous-value', $(this).prop('checked'));
    });
    
    $("input[name=myRadioGroup]").click(function () 
    {
        var previousValue = $(this).attr('previous-value');
    
        if (previousValue == 'true')
            $(this).prop('checked', false);
    });
    

提交回复
热议问题