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

Console
Get the value of selected radio button

Explanation

In the HTML tab,

  • Line 3: We import the jQuery package.
  • Line 6: We create a form with id='example'.
  • Line 7-10: We create two input elements of type radio with the name attribute as gender.
  • Line 12: We create a button with id='btn'.

In the JavaScript tab,

  • Line 3: We attach a click event on the button with id='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 value on the console.

Output

When the button is clicked, the value of the selected radio button will be printed on the console.

    Free Resources