Front-End & Daily

[JS] How to fix the issue where radio buttons cannot be unchecked with .prop("checked", false) when clicking a label

[JS] How to fix the issue where radio buttons cannot be unchecked with .prop(

When you want to uncheck a radio button by clicking the <label> tag

With jQuery, it would be something like this:

$("label").on("click", function(){
	$("input[type=radio]").prop("checked", false);
});

With vanilla JS, it seems like you could uncheck it like this:

document.querySelector("label").onclick(function(){
	document.querySelector("input[type=radio]").checked = false;
});

However, with this,

① Click the <label>

② JS unchecks it

③ The moment you release your finger, it gets checked again by its default behavior

This sequence occurs, and you cannot uncheck it.

Therefore,

Let's add a small delay with setTimeout.

$("label").on("click", function(){
	setTimeout(function(){
		$("input[type=radio]").prop("checked", false);
	}, 50); //50msの遅延
});

I've added a 50ms delay, but 1ms, or even 0ms for some reason, also worked.

However, I believe this depends on the user's machine specs, so I've set it to 50ms just in case.

The setTimeout syntax is the same for vanilla JS.

document.querySelector("label").onclick(function(){
	setTimeout(function(){
		document.querySelector("input[type=radio]").checked = false;
	}, 50) //50msの遅延
});

So, when you want to toggle the checked state of a radio button by clicking its label, remember to add a small setTimeout!

Comments

We also welcome reports such as "It worked!".

After reviewing the content, we will publish it, omitting any personal information.

Enter your name and email address

Please enter if you would like a reply via email.

The personal information you provide will not be disclosed. It will only be used for replying.

It will be sent directly. Please confirm and click "Send".

If this was helpful, we appreciate your support!
Your support will be used for childcare.

Send support via OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, "けん" earns from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark