Reputation: 127
I am learning some JQuery basics and am stumped on this particular situation. I have a basic table with a delete button at the end of each row and am trying to get my JQuery code to recognize the value of column 1 depending on which row I click the 'Delete' button on. It keeps giving me the value of the first row regardless of the row I am actually on.
Here is my code for the table:
<table id="DemoTable">
<thead><tr><th>Product</th><th>Price</th></tr></thead>
<tr><td>Sirloin Steak 10 oz.</td><td>8.77</td><td><input type="submit" value="Delete" /></td></tr>
<tr><td>Filet Mignon 8 oz.</td><td>14.50</td><td><input type="submit" value="Delete" /></td></tr>
<tr><td>Redi-Grill 5 oz.</td><td>1.55</td><td><input type="submit" value="Delete" /></td></tr>
<tr><td>San Marco Stuffed Shells</td><td>.35</td><td><input type="submit" value="Delete" /></td></tr>
<tr><td>Sliced Cheese Yellow</td><td>.10</td><td><input type="submit" value="Delete" /></td></tr>
</table>
And here is the JQuery section:
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var itemName = $('td:nth-child(1)', this).html();
return confirm('Are you sure you want to delete ' + itemName + '?');
});
});
</script>
Thanks for any help!
Upvotes: 1
Views: 5161
Reputation: 150040
Your code is running on the submit event of the form, so when you use this
it is the form itself rather than being the particular button that was clicked. Try handling the click event on the delete buttons, because then you can get the td that is in the same row as the button:
$('#DemoTable input[type="submit"]').click(function() {
var itemName = $(this).closest("tr").children().eq(0).html();
return confirm('Are you sure you want to delete ' + itemName + '?');
});
Demo: http://jsfiddle.net/nnnnnn/VxWUJ/
Note though that when the form is then submitted you need to do something with the value to be deleted, e.g., put it in a hidden field within the form. You don't show the rest of your form in the question, but it looks like the only form elements you have are the delete buttons.
Upvotes: 5
Reputation: 16959
try:
$('form').submit(function (e) {
var itemName = $(e.target).parents('tr').children(":first-child").html();
return confirm('Are you sure you want to delete ' + itemName + '?');
});
Upvotes: 1