You are viewing an old revision of this post, from November 8, 2021 @ 21:17:56. 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 (".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"); });


  • November 8, 2021 @ 21:17:56 [Current Revision] by Sharing Solution
  • November 8, 2021 @ 21:17:56 by Sharing Solution

Revision Differences

There are no differences between the November 8, 2021 @ 21:17:56 revision and the current revision. (Maybe only post meta information was changed.)

No comments yet.

Leave a Reply