Set a radio button with JavaScript/jQuery
This post will discuss how to set a radio button in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .prop() method to set the checked property of the radio button.
JS
|
1 2 3 |
$(document).ready(function() { $("#java").prop("checked", true); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java"> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" id="python" name="language" value="python"> <label for="python">Python</label> </div> </div> </body> </html> |
Alternatively, you can simply simulate the mouse-click for a radio button using jQuery’s .click() method. This is equivalent to calling .trigger('click').
JS
|
1 2 3 |
$(document).ready(function() { $("#java").click(); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java"> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" id="python" name="language" value="python"> <label for="python">Python</label> </div> </div> </body> </html> |
2. Using JavaScript
With plain JavaScript, you can use the checked property to set the value of a radio button.
JS
|
1 |
document.getElementById("java").checked = true; |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java"> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" id="python" name="language" value="python"> <label for="python">Python</label> </div> </div> </body> </html> |
That’s all about setting 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 :)