I have a quick jQuery question:
I have the following type of table:
<table id="my_table">
<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!
$(function() { $(":checkbox"). change(function () { $(this). parents(). children(':checkbox').
prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not.
You can do this: var isChecked = $("#rowId input:checkbox")[0]. checked; That uses a descendant selector for the checkbox, then gets the raw DOM element, and looks at its checked property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With