Reputation: 5305
As a jQuery newbie, I'm stumbling upon the following problem:
I have a button that appends a fieldset to an existing form. Works fine. Each fieldset furthermore has a button that ultimately is intended to delete that exact field again. For testing purposes, I bound a simple console.log to clicking on any of those delete buttons.
When I click on one of the delete buttons, the text is logged in the console. However, it only flashes for an instant before all previously appended fieldsets disappear completely from the document.
Here's the html
<form id="theform" class="form-inline">
<fieldset class="aField" id="field1">
<select id="products">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
<input type="text" placeholder="Amount" class="amount">
<input type="text" placeholder="Price">
</fieldset>
</form>
<button id="addtoform" class="btn test">New Product</button>
and here's the js:
$(document).ready(function () {
$('#addtoform').click(function() {
var fields = $('.aField').length;
var newField = 'field' + String(fields + 1);
var button = "<button class='btn btn-danger delete'>delete</button>";
var newElem = $('#field1').clone().attr('id', newField).append(button);
$('#theform').append(newElem);
});
$("#theform").on("click", '.btn.btn-danger.delete', function () {
console.log('ok, let me delete this.');
});
});
What is happening?
Upvotes: 1
Views: 1405
Reputation: 17366
Use this: you will it working and you can delete rest of the controls from the form.
$("#theform").on("click", '.btn.btn-danger.delete', function (e) {
e.preventDefault();
$(this).parent().remove(); // Delete appended element
console.log('Element Deleted..');
});
Upvotes: 1
Reputation: 864
Try this
$('.delete').click(function() {
$(this).parent().remove();
});
If your delete button is a child of your fieldset, this should remove only the parent fieldset.
Upvotes: 0
Reputation: 2804
This $("#theform .btn.btn-danger.delete')
selects all buttons. You have to single out the button you want to delete.
Or even easier is:
$(".btn.btn-danger.delete").click(function(){
$(this).remove();
});
Upvotes: 0