Uncheck a radio button with JavaScript/jQuery
This post will discuss how to uncheck a radio button in JavaScript and jQuery.
1. Using jQuery
The :checked CSS pseudo-class selector represents any radio (<input type="radio">) element that is checked. The idea is to use the :checked selector to identify the selected radio button and unset it.
jQuery
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $("input:radio[name=language]:checked")[0].checked = false; }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java" checked> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" name="language" value="python"> <label for="python">Python</label> </div> <button id="submit">Submit</button> </div> |
Alternatively, you can use the .prop() method to unset the value of matched radio elements, as shown below:
jQuery
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $("input[type=radio][name=language]").prop('checked', false); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java" checked> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" name="language" value="python"> <label for="python">Python</label> </div> <button id="submit">Submit</button> </div> |
2. Using JavaScript
In plain JavaScript, you can use the querySelector() method to return the selected radio button and set its checked property to false.
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var radio = document.querySelector('input[type=radio][name=language]:checked'); radio.checked = false; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java" checked> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" name="language" value="python"> <label for="python">Python</label> </div> <button id="submit">Submit</button> </div> |
That’s all about unchecking a radio button in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)