Logo

How can I know which radio button is selected via jQuery?

You can determine which radio button is selected by using jQuery’s :checked selector on the group of radio buttons (typically identified by their shared name attribute). For example:

<form> <input type="radio" name="myRadioGroup" value="Option1">Option 1 <input type="radio" name="myRadioGroup" value="Option2">Option 2 <input type="radio" name="myRadioGroup" value="Option3">Option 3 </form> <button id="checkButton">Check Selection</button>
$('#checkButton').on('click', function() { // Grab the value of the currently selected radio button const selectedValue = $('input[name="myRadioGroup"]:checked').val(); if (selectedValue) { console.log('Selected radio button:', selectedValue); } else { console.log('No radio button is selected.'); } });
  • How It Works: The jQuery :checked pseudo-class filters the set of radio buttons to the one that’s currently selected.
  • .val(): Returns the value attribute of the selected radio button. If none is selected, it returns undefined.

Additional Tips

  1. Make sure all radio buttons in the group share the same name attribute so that only one can be selected at a time.
  2. You can also use $('input[name="myRadioGroup"]:checked') to access the DOM element itself—for example, .attr('id'), .data(), etc.

Level Up Your JavaScript Skills

For a deeper dive into JavaScript and DOM manipulation (including jQuery fundamentals), explore these courses on DesignGurus.io:

You can also watch the DesignGurus.io YouTube channel for free tutorials and discussions on coding best practices, system design, and more.

CONTRIBUTOR
TechGrind