Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add and remove div using jquery

I'm making a scenario where user will be able to add a new row with "Remove" option by clicking "Add" button. If they click "Remove" button, the entire row will be deleted. I've put script for it. But, it's not working perfectly. Kindly, take a look on my fiddle: http://jsfiddle.net/learner73/gS8u2/

My problem is:

(1) If user click "Add" button, a new row will be added. That's good. But, it's gone below the "Add" button. I want, the new row will be added above the "Add" button, I mean "Add" button should be always at the bottom.

(2) At my code, if user click "Remove" button on the previously created row, the entire row will be deleted. That's good. But, when they click "Remove" button on dynamically created row, nothing will happened!

HTML:

<div class="optionBox">
    <div class="block">
        <input type="text" /> <span class="remove">Remove Option</span>
    </div>
    <div class="block">
        <input type="text" /> <span class="remove">Remove Option</span>
    </div>
    <div class="block">
        <span class="add">Add Option</span>
    </div>
</div>

jQuery:

$('.add').click(function() {
    $('.optionBox').append('<input type="text" /><span class="remove">Remove Option</span>');
});

$('.remove').click(function() {
    $(this).parent('div').remove();
});
like image 497
user1896653 Avatar asked May 05 '14 21:05

user1896653


1 Answers

You need to use event delegation on your remove link code:

$('.add').click(function() {
    $('.block:last').before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$('.optionBox').on('click','.remove',function() {
    $(this).parent().remove();
});

jsFiddle example

Also, you weren't adding a complete div block to match the other code you had. You left out the <div class="block"> and only added the input and span.

like image 128
j08691 Avatar answered Sep 20 '22 22:09

j08691