You are viewing an old revision of this post, from February 9, 2022 @ 18:54:36 [Autosave]. See below for differences between this version and the current revision.

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

Revision Differences

There are no differences between the February 9, 2022 @ 18:54:36 [Autosave] revision and the current revision. (Maybe only post meta information was changed.)

No comments yet.

Leave a Reply