Toggle a radio button with jQuery
This post will discuss how to implement a toggle in an HTML radio button with jQuery.
The following code example demonstrates how to implement toggle when there are only two radio buttons:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('input[type="radio"]').not(':checked').prop("checked", true); }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <label><input type="radio" name="language" value="java" checked>Java</label> <label><input type="radio" name="language" value="cpp">C++</label> </div> <button id="submit">Submit</button> </div> </body> </html> |
If there are more than two radio buttons, you can use the following code:
JS
|
1 2 3 4 5 6 7 8 9 10 11 |
$(document).ready(function() { $('#submit').click(function() { var radios = $('input[type=radio]') var current = radios.filter(':checked'); var next = radios.eq(radios.index(current) + 1); if (next.length === 0) { next = radios.first(); } next.prop('checked', true); }); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <label><input type="radio" name="language" value="java" checked>Java</label> <label><input type="radio" name="language" value="cpp">C++</label> <label><input type="radio" name="language" value="python">Python</label> </div> <button id="submit">Submit</button> </div> </body> </html> |
That’s all about toggling a radio button with 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 :)