jQuery How is a radio button unchecked, if there’s only one button

  • Post author:
  • Post category:jQuery

If you have a single radio button and you want to allow the user to uncheck it using jQuery, you can do so by toggling its “checked” property. Here’s an example of how to achieve this:

$(document).ready(function() {
  // Target the radio button by its ID
  var $radioButton = $('#myRadioButton');

  // Add a click event handler to the radio button
  $radioButton.on('click', function() {
    if ($radioButton.is(':checked')) {
      // If the radio button is checked, uncheck it
      $radioButton.prop('checked', false);
    } else {
      // If the radio button is not checked, check it
      $radioButton.prop('checked', true);
    }
  });
});