4

How to (un)check a radio input element on click of the element or its container?

I have tried the code below, but it does not uncheck the radio.

HTML:

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

jQuery:

$(".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") {
        $(this).find(".il-radio").removeAttr("checked");
    }
});
rdans
  • 2,179
  • 22
  • 32
funerr
  • 7,212
  • 14
  • 81
  • 129
  • 1
    why dont you just use label in its original form? http://www.w3schools.com/tags/tag_label.asp – Oriesok Vlassky Mar 16 '12 at 13:27
  • 2
    @OriesokVlassky: Because that would require every input control to have an ID, in order for the label to refer to it. `` is valid HTML; it should work. – cHao Mar 16 '12 at 13:31
  • Check http://stackoverflow.com/questions/2117538/jquery-how-to-uncheck-a-radio-button – Gert Grenander Mar 16 '12 at 14:04

3 Answers3

6

radio buttons don't uncheck, you need to use a checkbox (type = 'checkbox')

CKKiller
  • 1,424
  • 1
  • 16
  • 20
6

You have to prevent the default behaviour. Currently, on click, the following happens:

  1. click event fires for the container (div.is).
  2. click event fires for the label.
  3. Since your function toggles a state, and the event listener is called twice, the outcome is that nothing seems to happen.

Corrected code (http://jsfiddle.net/nHvsf/3/):

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

    // Ignore the event when the radio input is clicked.
    if (!$(event.target).is(radio_selector)) {
        $radio = $(this).find(radio_selector);
        // Prevent the event to be triggered
        // on another element, for the same click
        event.stopImmediatePropagation();
        // We manually check the box, so prevent default
        event.preventDefault();
        $radio.prop('checked', !$radio.is(':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;
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

use only html , same functionality

<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio"  /> Is </label>
sandeep
  • 2,244
  • 1
  • 23
  • 38
  • 1
    The `for` attribute is not needed when the control is the only one within the label. – cHao Mar 16 '12 at 13:35