jQuery: How can select clicked element in table without define unique id for each element
I have table (that generated by server) below.
I want to get input element value class="itemQuantity"
of clicked row.
I write jQuery code but he missing "this" of clicked element.
<script type="text/javascript">
$(document).ready(function() {
$('.updateButton').click(function() {
alert($('.itemQuantity').val());
});
});
</script>
How can I do it with jQuery (I 开发者_如何学Cthinking to use this and not create id for each element, but I have low knowledge in jQuery).
Thanks, Yosef
<table id="items">
<tr>
<th>item id</th>
<th>item name</th>
<th>item quantity</th>
<th>item update</th>
</tr>
<tr>
<td class="itemID">
1
</td>
<td class="itemName">
Ferari
</td>
<td >
<input class="itemQuantity" type="text" size="4" />
</td>
<td>
<button class="updateButton">update item</button>
</td>
</tr>
<tr>
<td class="itemID">
2
</td>
<td class="itemName">
Fiat
</td>
<td >
<input class="itemQuantity" type="text" size="4" />
</td>
<td>
<button class="updateButton">update item</button>
</td>
</tr>
<tr>
<td class="itemID">
3
</td>
<td class="itemName">
Hundai
</td>
<td >
<input class="itemQuantity" type="text" size="4" />
</td>
<td>
<button class="updateButton">update item</button>
</td>
</tr>
</table>
$(document).ready(function() {
$('.updateButton').click(function() {
alert($(this).closest('tr').find('.itemQuantity').val());
});
});
In jQuery event handlers "this" will refer to the DOM element that is the source of the event. So in your click() function you can use either this or $(this) if you need a wrapped object.
If your HTML is fixed you can also achieve the same result with parent():
<script type="text/javascript">
$(document).ready(function() {
$('.updateButton').click(function() {
alert($(this).parent().parent().find('.itemQuantity').val());
});
});
</script>
精彩评论