How to know which radio button is selected using jQuery
In jQuery, to know which radio button is selected, we first need to find the desired input group. We can achieve this by using the name attribute of the input element as below.
$('input[name=gender]:checked', formId)
The above will select all the input groups that have the name attribute as gender in the specified form. We can then use the val() method to get the value of the selected radio button as below.
$('input[name=gender]:checked', formId).val()
Example
Explanation
In the HTML tab,
- Line 3: We import the
jQuerypackage. - Line 6: We create a form with
id='example'. - Line 7-10: We create two
inputelements of typeradiowith thenameattribute asgender. - Line 12: We create a button with
id='btn'.
In the JavaScript tab,
- Line 3: We attach a
clickevent on the button withid='btn'. - Line 5: When the button is clicked, we get the value of the selected radio button and store it in the variable
value. - Line 8: We print
valueon the console.
Output
When the button is clicked, the value of the selected radio button will be printed on the console.