Matt Pierce
Matt Pierce

Reputation: 805

Jquery Insert in DOM and Remove from DOM

Super simple, but I'm flabbergasted. I have a simple script to load an input to the DOM on click.

$('.add-more-games').find('button').click(function(){
    var gameInput = [
                    '<div class="form-group">',
                    '<input type="text" name="gameInfo[]" class="form-control input-global add-detail-input"/>',
                    '<span class="glyphicon glyphicon-remove detail-input-remove"></span>',
                    '</div>'
                    ].join('');

    $(gameInput).insertBefore('.add-more-games');
});

$('.detail-input-remove').click(function(){
    $(this).parent('.form-group').detach();
});

Now, within the gameInput variable, there's a span element with the "detail-input-remove" class. I do some CSS to have that "X" hover over the input element and it becomes visible when I focus on the input element. All I want to do is click that "X" and .detach() that form-group from the DOM. When I click, it doesn't respond to anything (even a simple "hello world" alert). Is this because that element isn't in the DOM when the page loads?

Upvotes: 0

Views: 61

Answers (5)

IshanJain
IshanJain

Reputation: 126

You can use something like that.

   $(".detail-input-remove").live('click', function() {
       alert('you clicked!');
       $(this).parent('.form-group').detach();
   });

Also I have made an example please use below fiddle link this works for me.

https://jsfiddle.net/Isjain/98x9760a/1/

Hope this will work for you.

Thanks

Upvotes: 0

Jithu Rajan
Jithu Rajan

Reputation: 452

$('.detail-input-remove').click(function(){
  $(this).parent('.form-group').detach();
});

the above line add a click event listener to all element having class 'detail-input-remove' which all are available in dom at that time. Since you are adding form-group on click, the above mentioned event will not be registered for span with class detail-input-remove inside the form-group.

You need to define the event as delegate.

$(document).on('click', '.detail-input-remove', function(){
  $(this).parent('.form-group').empty();
});

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Use delegation,learn about delegation

$('body').on('click','.detail-input-remove',function(){
    var detached_element = $(this).parent('.form-group').detach();
});

jsfiddle:https://jsfiddle.net/vgy2t1gq/

Upvotes: 0

Davor Minchorov
Davor Minchorov

Reputation: 2076

Try

$(document).on('click', '.detail-input-remove', function(){
    $(this).parent('.form-group').empty();
});

Upvotes: 1

rt2800
rt2800

Reputation: 3045

Change $(this).parent('.form-group').detach(); to $(this).parent('.form-group').remove();

Upvotes: 0

Related Questions