Javascript – How to check and uncheck radio button on click

I was working with a client who was required to be able to uncheck the checked radio.

I was struggling for many hours with that request.

Finally, I find out a solution to solve that issue with Javascript.

The solution is to track the selected state manually using the “click” event handler and a custom class state.

Handle the click events on the radio input elements and check if the “selected” class exists on the clicked element.

If it does, (meaning it has been clicked before), remove the class and uncheck the element.

If it doesn’t, remove the class from all elements of the same name and add it to only the clicked element.

Here is the code in Jquery:

$(“input:radio”).on(“click”,function (e) {
var inp=$(this); //cache the selector
if (inp.is(“.theone”)) { //see if it has the selected class
inp.prop(“checked”,false).removeClass(“theone”);
return;
}
$(“input:radio[name='”+inp.prop(“name”)+”‘].theone”).removeClass(“theone”);
inp.addClass(“theone”);
});

Revisions

No comments yet.

Leave a Reply