I’m trying to add a button that contains the .closest & .remove into an .append but only the existing button works. I want to be able to click the “New Line” button and have a new line .append and then also be able to “Remove” any of the lines that get added but only the one in that line.
The button
<button id="addLine">New Line</button>
when clicked adds a new table to the
<div id="orderForm">
This is what is added
$('#orderForm').append('<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0"><tr><td><input name="field1" type="text" id="field1" size="25" tabindex="1"></td><td><button id="removeLine">remove()</button></td></tr></table>');
Thats fine and working. I’ve also added
$("#removeLine").click(function () {
$('#removeLine').closest('.orderLine').remove();
});
BUT it only works on the first line that was existing.
Here is the full code.
<html>
<head>
<?php include '../_includes/jq.inc.php';?><br>
</head>
<body>
<button id="removeAll">Delete All</button>
<button id="addLine">New Line</button>
<div id="orderForm">
<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input name="field1" type="text" id="field1" size="25" tabindex="1"></td>
<td><button id="removeLine">remove()</button></td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
$("#removeLine").click(function () {
$('#removeLine').closest('.orderLine').remove();
});
<!-- This removes all newLine table rows -->
$("#removeAll").click(function () {
$('.orderLine').remove();
});
<!-- ADDS the 'newLine' table rows -->
$("#addLine").click(function () {
$('#orderForm').append('<table class="orderLine" width="90%" border="0" cellspacing="0" cellpadding="0"><tr><td><input name="field1" type="text" id="field1" size="25" tabindex="1"></td><td><button id="removeLine">remove()</button></td></tr></table>');
});
</script>
</html>
I’ve checked it over and checked it over and I have no idea what I’m doing wrong. Does anyone have any ideas on this?
No two elements can have the same
id– use classes and event delegation:HTML:
JS:
Delegation lets you listen to events triggered by elements that have not yet been added to the document. In this case, it attaches a handler to
orderFormthat listens to click events triggered on.removeLineelements that either currently exist or will be added in the future.