Reputation: 34208
suppose i have html table and each TR has id. every TR has some TD and some TD has input controls and some may have text inside in.
when click on TD or control should return immediate TR id.
i tried this below script which works fine but when i click on text like hello1 then TR id does not return.
see the script and tell me what is missing.
<div id="grd1">
<table>
<tr id="t1"><td tabindex="0"><span>Hello1</span></td><td tabindex="1"><input /></td><td tabindex="2"><input /></td></tr>
<tr id="t2"><td tabindex="3"><span>Hello2</span></td><td tabindex="4"><input /></td><td tabindex="5"><input /></td></tr>
</table>
</div>
$('#grd1 table tr').on('focus', ':input', function(event) {
alert($(this).closest('tr').attr('id'));
});
Upvotes: 0
Views: 3256
Reputation: 5109
Give the table an id eg 'table':
$('#table').children('tbody').children('tr').each(function () {
var $row = $(this);
$row.find('input').on('focus', function () {
alert($row.get(0).id);
});
});
Upvotes: 0
Reputation: 167240
Since you are using an advanced selector, I suggest you do some changes:
:input
to input
.id
call, change it to below.<tr>
is also dynamic, so add it with the delegation.Corrected Code:
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<div id="grd1">
<table>
<tr id="t1"><td tabindex="0"><span>Hello1</span></td><td tabindex="1"><input /></td><td tabindex="2"><input /></td></tr>
<tr id="t2"><td tabindex="3"><span>Hello2</span></td><td tabindex="4"><input /></td><td tabindex="5"><input /></td></tr>
</table>
</div>
<script>
$('#grd1 table tr').on('click focus', 'td, input, th', function(event) {
alert($(this).closest('tr').attr('id'));
});
</script>
The Alert Duh!!!
Upvotes: 0