How to check/uncheck radio button on click?

后端 未结 18 1455
情深已故
情深已故 2020-11-29 02:16

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

<
18条回答
  •  盖世英雄少女心
    2020-11-29 02:16

    Here's a super lightweight script you can add to a page through the console window that allows you to deselect a radio button by holding down Ctrl while clicking it with the mouse.

    document.addEventListener('click', function(e){
       if (e.ctrlKey == true && 
           e.target.tagName == 'INPUT' && 
           e.target.type == "radio" && 
           e.target.checked == true) {
           e.target.checked = false;
       }
    });
    

    Since it doesn't rely on jQuery, you can easily add it to any page to temporarily allow deselection.
    For slightly more info, you can read an article I just wrote on How To Deselect A Radio Button.

提交回复
热议问题