Reputation: 951
I have a table which rows are generated with a click event of an element. Now, this works perfectly, the problem is with the delete part. For example I have already added 5 rows, when I click the delete button (the delete button is created through jQuery too on the addRow() click event), all rows added through the jQuery function are being deleted and the form is submitting event though I have an e.preventDefault() method called.
JavaScript/jQuery code:
var counter = 2;
window.addRow = function addRow() {
var newRow = $('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' + counter + '"/></td><td><button class="delete">delete</button></td></tr>');
counter++;
$('table.actionsteps-list').append( newRow );
}
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
function postForm() {
var form = document.getElementById('actionStepsForm');
document.getElementById('rowCount').value = counter-1;
form.submit();
}
HTML Code (the form itself):
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td>
<label>1</label>
</td>
<td>
<textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea>
</td>
<td valign="top">
<input type="text" name="txtOwner1" />
</td>
</tr>
</table>
<table width="510">
<tr>
<td align="right"><a href="#" title="" onclick="addRow(); return false;">Add Action</a></td>
</tr>
</table>
<input type="button" value="Create" onclick="postForm(); return false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>
Believe it or not, I've been stuck here for almost 3 days now. I can't find any fix online. I don't what's wrong.
Upvotes: 0
Views: 3065
Reputation: 9583
put
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
into
$(function(){$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
)};
Upvotes: 1