SPG
SPG

Reputation: 6197

jquery remove() problem

See HERE!!! http://jsfiddle.net/y5gbg/ When I type something, it should append a round div and text. When I click this round div, it should be removed. This is jquery code:

$(document).ready(function(){


    $("button").click(function(){
     var str;
     str = $('input').val();
     var sth;
     sth = '<div id="'+str+'"><div class="btn" alt="'+str+'"></div><p>'+str+'</p><hr></div>';
     $("#contents").append(sth);
    });

    $('.btn').click(function(){
      var id;
      id = $(this).attr('alt');
      $('#'+id).remove();    
    });

});

But it doesn't work. Could someone tell me why? Another thing, how to do linebreak here? Thanks!!!

Upvotes: 0

Views: 615

Answers (5)

ayyp
ayyp

Reputation: 6598

If you only need the button removed then your code would be:

$('.btn').live("click", function(){
   $(this).remove();    
});

instead of what you currently have for $('.btn')...

Upvotes: 1

Brian Hoover
Brian Hoover

Reputation: 7991

You need to use the live function for the second function

$('.btn').live('click',function(){
  var id;
  id = $(this).attr('alt');
  $('#'+id).remove();    
});

Upvotes: 0

Gabe
Gabe

Reputation: 50493

You need to use live()

Here is your updated jsFiddle

Upvotes: 0

Joseph
Joseph

Reputation: 25513

you just need to use the live function

$('.btn').live('click', function(){
  var id;
  id = $(this).attr('alt');
  $('#'+id).remove();    
});

because you're adding the div to the dom dynamically so the click isn't getting registered to the div

Here's an example of it working.

Upvotes: 4

Umur Kontacı
Umur Kontacı

Reputation: 35478

you can try $('#'+id).hide();

Upvotes: 0

Related Questions