We can use jQuery to get the value of a radio button using the jQuery val() method.
$('input[name="radio1"]:checked').val();
Where radio1 in the code above would be the name attribute that all of the radio buttons share.
If using WordPress, don’t forget to change the $ to jQuery:
jQuery('input[name="radio1"]:checked').val();
Let’s see an example of this below.
Lets say we have the following HTML:
Select your favorite mode of transportation:
In this example, the checked radio button to start will be the Train option. We can use our code above to get this value using jQuery.
Here is the jQuery code we will need:
var selectedRadioButton = $('input[name="transport"]:checked').val();
Try it out below by selecting a radio button and then clicking the button below to see what radio button is checked:
Code Output:
Select your favorite mode of transportation:
Full Code:
Select your favorite mode of transportation:
Check which radio button is selected with jQuery
Using jQuery to Set the Value of a Radio Button
We can also use jQuery to set the value of a radio button. We simply need to change the checked property of the radio button to true. Here is how we can do this:
$("#airplane").prop("checked",true);
Let’s see this in a similar example to the one above.
Code Output:
Select your favorite mode of transportation:
Full Code:
Select your favorite mode of transportation:
Set the radio button Airplane to checked