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

To determine which radio button is selected using jQuery, you can use the :checked selector combined with the radio button group’s name attribute. Here’s how:

Method 1: Get the Value of the Selected Radio Button

// Get the value of the selected radio button in a group
const selectedValue = $('input[name="yourRadioGroupName"]:checked').val();

// Example usage:
// HTML: <input type="radio" name="color" value="red"> Red
//       <input type="radio" name="color" value="blue"> Blue
const color = $('input[name="color"]:checked').val();
console.log(color); // Output: "red" (if selected)

Method 2: Check If a Specific Radio Button Is Selected

// Check if a specific radio button is selected (by ID, value, etc.)
const isSelected = $('#radioButtonId').prop('checked');

// Example:
if ($('#redRadio').prop('checked')) {
  console.log("Red is selected!");
}

Method 3: Iterate Over All Radio Buttons in a Group

// Loop through all radio buttons in the group and find the selected one
$('input[name="yourRadioGroupName"]').each(function() {
  if ($(this).prop('checked')) {
    console.log("Selected value:", $(this).val());
  }
});

Handling No Selection

If no radio button is selected, the :checked selector returns undefined or an empty jQuery object. Handle this case gracefully:

const selectedValue = $('input[name="color"]:checked').val();
if (selectedValue) {
  console.log("Selected:", selectedValue);
} else {
  console.log("No radio button selected!");
}

Full Example

<form>
  <input type="radio" name="size" value="small"> Small
  <input type="radio" name="size" value="medium"> Medium
  <input type="radio" name="size" value="large"> Large
</form>

<button id="checkButton">Check Selection</button>

<script>
$(document).ready(function() {
  $('#checkButton').click(function() {
    const selectedSize = $('input[name="size"]:checked').val();
    if (selectedSize) {
      alert("Selected size: " + selectedSize);
    } else {
      alert("No size selected!");
    }
  });
});
</script>

Key Notes

  • Use :checked to filter the selected radio button(s).
  • Always reference the radio group by its name attribute.
  • Use .prop('checked') to check the state of a specific radio button.
  • If your radio buttons are dynamically added, use event delegation (e.g., $(document).on('change', 'input[name="..."]', ...)).

This approach works for both radio buttons and checkboxes, but since radio buttons are mutually exclusive, only one will ever be selected.

Leave a Reply

Your email address will not be published. Required fields are marked *