I have this markup :
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
The desired functionality is to select the radio either by clicking parent div
or the radio input itself and if the radio is already checked then click on parent will have no effect i.e return false.
I have made it to change on click of parent, but when i click on the radio button , nothing happens. What's wrong with my approach ?
jQuery :
$('input:radio').closest('div').on('click', function (e) {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
console.log("Clicked : " + $(this).attr('class'));
});
Fiddle : http://jsfiddle.net/pSSc9/1/
$('.A').on('click', function (e) {
if ($(e.target).is('.B')) {
e.stopPropagation();
// So that event does not bubble when radio is selected
} else {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
}
console.log("Clicked : " + $(e.target).attr('class'));
});
The problem with your code was you were returning false when the checkbox is clicked. So you were indirectly doing event.preventDefault()
and event.stopPropagation()
by doing return false;
You explicitly need to set the checked property to true only when clicked on the div. But when you click on the radio it performs the default action. So you need to stop the propagation of the event.