exexe
exexe

Reputation: 196

Jquery - Removing appended code not worked

I have problem with removing appended code.
Try add some div's and check results.
When you try dblclicked on new div, he won't be removed.

HTML:

<input id="val" name="value" />
<input id="submit" type="button" value="ok" />
<div id="content"></div>

Script:

$("div[id^='block_']").on('dblclick', function() {
 $(this).remove();
});

$("#submit").click(function(){
 if ( $('#val').val().length > 0 )
 {
  $('#content').append('<div id="block_'+ $('#val').val() +'">'+ $('#val').val() +'</div>');

  $('#val').val('');
 }
});

Here's JSFiddle
I use jquery 2.0.3.

Upvotes: 1

Views: 84

Answers (4)

Juan
Juan

Reputation: 5050

another way would be creating the div and assigning the event before appending it to the dom

var div = $('<div id="block_'+ $('#val').val() +'">'+ $('#val').val() +'</div>');

div.on('dblclick',function(){$(this).remove();});
$('#content').append(div);

jfiddle

Upvotes: 0

Kevin Harrison
Kevin Harrison

Reputation: 337

Why do you have this part in your code?

$("div[id^='block_']").on('dblclick', function() {
 $(this).remove();
});

If you're doing this because you want to select the ID of a div tag as the selector you don't have to do it this way.

For example if you want to remove you would do this:

$("#content").on('dblclick', function() {
 $(this).remove();
});

Upvotes: 0

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

As your divs are generated dynamically so use event Delegation with .on():

$(document.body).on('dblclick',"div[id^='block_']", function() {
    $(this).remove();
});

Fiddle Example

Upvotes: 1

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Your element is not there when you are binding the click event. Use delegeted event :

$('#content').on('dblclick', "div[id^='block_']", function() {
    $(this).remove();
});

Here all the information you need : http://api.jquery.com/on/#direct-and-delegated-events

Upvotes: 1

Related Questions