jQuery Find child Checkbox
I have a quick jQuery question:
I have the following type of table:
<table id="my_table">
&开发者_StackOverflowlt;tr>
<td><input type="checkbox" value="24"></td>
<td> Click Here To Check The Box </td>
<td> Or Click Here </td>
</tr>
</table>
And in jQuery, I am attempting to select the corresponding checkbox in that row that was clicked.
$("#my_table tr").click(function(e) {
$(this).closest(":checkbox").attr("checked", checked");
});
But the above isn't working. Any quick ideas on selecting the checkbox on the row that was clicked? Thanks!
EDIT: BEST SOLUTION AT BOTTOM
Assuming there's only one checkbox, I would attach the event to the td
instead of the tr
:
$('#my_table td').click(function(e){
$(this).parent().find('input:checkbox:first').attr('checked', 'checked');
});
Example
If you want to be able to uncheck the checkbox as well...
$('#my_table td').click(function(e) {
var $tc = $(this).parent().find('input:checkbox:first'),
tv = $tc.attr('checked');
$tc.attr('checked', !tv);
});
This function needs to be applied to the checkbox as well to negate the default behavior.
Example 2
EDIT: The solution is most reasonable method is to cancel the functionality if the target is an input: http://jsfiddle.net/EXVYU/5/
var cbcfn = function(e) {
if (e.target.tagName.toUpperCase() != "INPUT") {
var $tc = $(this).parent().find('input:checkbox:first'),
tv = $tc.attr('checked');
$tc.attr('checked', !tv);
}
};
$('#my_table td').live('click', cbcfn);
The jQuery closest() method finds the closest parent.
You really want to search child elemets, You can try the following:
$("#my_table tr").click(function(e) {
$(":checkbox:eq(0)", this).attr("checked", "checked");
});
basically you are searching for the first checkbox found in the table row
some reference
jQuery :eq() selector
......
$("#my_table tr").click(function(e) {
state= $(this).find(":checkbox:eq(0)").attr("checked");
if (state==true){ // WITH TOGGLE
$(this).find(":checkbox:eq(0)").removeAttr("checked");
}else {
$(this).find(":checkbox:eq(0)").attr("checked", "checked");
}
});
I make simple script to check first checkbox in specific tr. about toggle i just make it to try before post this answer.
try this also...
$("#my_table tr").click(function(e) {
$(this).closest("type:checkbox").attr("checked", checked");
});
精彩评论