jQuery check/uncheck radio button onclick

前端 未结 24 2805
滥情空心
滥情空心 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:42

    -- EDIT --

    It sure looks like your code is forcing a radio input to behave like a checkbox input. You might think about just using a checkbox input without the need for jQuery. However, if you want to force, like @manji said, you need to store the value outside the click handler and then set it on each click to the opposite of what it is at that time. @manji's answer is correct, I would just add that you should cache jQuery objects instead of re-querying the DOM:

    var $radio = $("#radioinstant"),
        isChecked = $radio.attr("checked");
    
    $radio.click(function() {
    
        isChecked = !isChecked;
        $(this).attr("checked", isChecked);
    
    });
    

提交回复
热议问题