How to toggle the check state of a radio input element when pressed?

How to (un) check a radio input element when the element or its container is clicked?

I've tried the code below, but it doesn't turn off the radio.


<div class="is">
    <label><input type="radio" name="check" class="il-radio" /> Is </label>
    <img src="picture" />



$(".is label, .is ").click(function () {
    if (!$(this).find(".il-radio").attr("checked")) {
        $(this).find(".il-radio").attr("checked", "checked");
    } else if ($(this).find(".il-radio").attr("checked") == "checked") {



source to share

3 answers

You must prevent default behavior. Currently, when pressed, the following happens:

  • click

    event is fired for container (

  • click

    the event fires for the label.
  • Since your function is to toggle state and the event listener is called twice, the result is that nothing happens.

Corrected code ( ):

$(".is").click(function(event) {
    var radio_selector = 'input[type="radio"]',

    // Ignore the event when the radio input is clicked.
    if (!$( {
        $radio = $(this).find(radio_selector);
        // Prevent the event to be triggered
        // on another element, for the same click
        // We manually check the box, so prevent default
        $radio.prop('checked', !$':checked'));
$(".il-radio").on('change click', function(event) {
    // The change event only fires when the checkbox state changes
    // The click event always fires

    // When the radio is already checked, this event will fire only once,
    //   resulting in an unchecked checkbox.
    // When the radio is not checked already, this event fires twice
    //   so that the state does not change
    this.checked = !this.checked;




Pluggable buttons

are not unchecked, you need to check the box (type = 'checkbox')



use html only, same functionality

<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio"  /> Is </label>




All Articles