How To Toggle The Check State Of A Radio Input Element On Click?
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:
&l
Solution 1:
You have to prevent the default behaviour. Currently, on click, the following happens:
click
event fires for the container (div.is
).click
event fires for the label.- 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 clickevent.stopImmediatePropagation();
// We manually check the box, so prevent defaultevent.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 changethis.checked = !this.checked;
});
Solution 2:
Solution 3:
use only html , same functionality
<label for="rdio"><input type="radio" name="rdio"id="rdio" class="il-radio" /> Is </label>
Post a Comment for "How To Toggle The Check State Of A Radio Input Element On Click?"