Reputation: 431
I have a text input field, next to this there is a button. When I click this button, I want alert() to show me the ID of the input field. This is my code
<tr>
<td>Item <?php echo $i; ?>:</td>
<td>
<input type="text" name="course_include_1" class="regular-text" /> <input type="button" class="button" id="DeleteItem" value="Delete Item" />
</td>
</tr>
And this is my jQuery code:
$("#DeleteItem").live("click", function() {
//$(this).parents("tr").remove();
alert($(this).prev().attr("id"));
});
Why is this not working?
Edit: I should add that the there is also a "Add" button which creates a new input field along with the delete button next to it. The code for this looks like this:
$("#AddItem").live("click", function() {
Count++;
$('<tr><td>Item ' + Count + ':</td><td><input id="asdadad" name="course_include_' + Count + '" type="text" class="regular-text" /> <input type="button" class="button" id="DeleteItem" value="Delete Item" /></td></tr>').appendTo(TableRow);
});
The goal is to click on the delete button next to the newly created field and show its ID in an alert() box. And that's not working.
Upvotes: 0
Views: 1608
Reputation: 1596
Q: Why is this not working? A: The input has no id attribute
Edit
Now you have many elements with id="DeleteItem"
which may well cause 'unexpected' browser behaviour (eg. mess up the binding). Use a class instead, changing this in the line when you append the new item:
class="button" id="DeleteItem"
to this:
class="button DeleteItem"
...and in the event binding change this:
$("#DeleteItem").live("click", function() {
to this:
$(".DeleteItem").live("click", function() {
or even to this (it is recommended to use .on()
instead of .live()
, see first text paragraph here):
$(document).on('click','.DeleteItem', function() {
That might resolve things
Edit 2
ps. I would also make a unique id
for each input element, eg. ... id="asdadad"'+Count+' ...
or move it to the class if they are supposed to be the same for every item added
Upvotes: 1
Reputation: 487
it's not answering your question but it will DELETE the row all together if you do this...
<input type='button' value='delete' onclick="$(this).parents('tr').remove();" />
parents (vs parent) will do a 'find' but upward until it finda the <tr>
holding the row... then remove will 'delete' it.
PS: If you have multiple tow, and multiple delete button they need UNIQUE id's or jq get confused sometimes.
Upvotes: 0
Reputation: 337560
Try this:
$("#DeleteItem").live("click", function() {
alert($(this).parent().find(".regular-text").attr("id"));
});
Update
The problem is because you are appending an element with a duplicate id
attribute. Change the #DeleteItem
to use a class instead.
Upvotes: 0
Reputation: 2448
Because the input doesn't have an id attribute set e.g.
<input id='myInput' type="text" name="course_include_1" class="regular-text" />
Upvotes: 1