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.
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:to this:
…and in the event binding change this:
to this:
or even to this (it is recommended to use
.on()instead of.live(), see first text paragraph here):That might resolve things
Edit 2
ps. I would also make a unique
idfor 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