Jquery event on wrapped input radio override 'checked' event
I want to check and uncheck (toggle) the radio when "td" is click but preserving the default input event
<table>
<tr>
<td>
<input type='radio'>
</td>
</tr&g开发者_StackOverflowt;
</table>
My code attempts:
Try 1: http://jsfiddle.net/UJXRu/
Try 2: http://jsfiddle.net/UJXRu/1/
Try 3: http://jsfiddle.net/UJXRu/2/
Preview:
$("td").click(function(e) {
if (!$(e.target).is("input")) {
var bool = !$(this).children("input").is(':checked');
$(this).children("input").attr("checked", bool)
}
else{
var bool2 = !$(e.target).is(':checked');
$(e.target).attr('checked',bool2);
}
});
Try this out..
$("td").click(function(e) {
if (e.target.type !== 'radio') {
$(this).find(":radio").trigger('click');
}
});
Example on jsfiddle.
If you want to make the td and radio button toggle the radio checked property you could do something like this:
$("td").toggle(function() {
$(this).children(":radio").attr("checked", true);
}, function() {
$(this).children(":radio").attr("checked", false);
});
Example on jsfiddle
Responding to your comment:
"i want to check radio button when I click both td or the radio button"
Should be as simple as:
$("td").click(function(e) {
$(this).find("input").attr("checked", true);
});
http://jsfiddle.net/lukemartin/UJXRu/3/
This answer doesn't treat radio buttons as check-boxes (Users really don't like that) and attempts to provide a slightly more realistic scenario.
$("tr.myRow").click(function(e) {
// dont override the radio inputs default
if ($(e.target).hasClass("childRadio") || e.target.tagName == 'LABEL')
return;
// find the child radio, and if it's not checked, check it.
var $childRadio = $("input.childRadio", $(this));
if (!$childRadio.attr('checked')) {
$childRadio.attr('checked', 'checked');
}
});
I've gone to the trouble of adding labels, and have used the name property so that the radio buttons are grouped (which is the reason to have a radio buttons). So this keeps as much default behavior as possible, and is just augmenting clicks to select a specific child radio button.
The html sample is below.
<tr class="myRow">
<td>
<div>Some Content</div>
<div>
<label for="radio1">Radio 1 Label</label>
<input type='radio' id="radio1" class="childRadio" checked="checked" name="Group1">
</div>
<div>More Content</div>
</td>
</tr>
<tr class="myRow">
<td>
<div>
<label for="radio2">Radio 2 Label</label>
<input type='radio' id="radio2" class="childRadio" name="Group1">
</div>
</td>
</tr>
Why not just call the default click event on the input tag:
$(this).children("input").click();
精彩评论