[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(](img/ogp.png)
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!".




If this was helpful, we appreciate your support!
Your support will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR