DavidR
DavidR

Reputation: 5388

Jquery/Javascript: Buttons added dynamically with javascript do not work

I have a code chunk of html:

<div id="chunk-1" class="chunk">  
    <div class="chunkText">Text<div>  
    <button class="addChunk">Click Me</button>  
</div>

<script>

$(".addChunk").click(function(){create_chunk(this.parentNode)})

function create_chunk(after_this){
    $(after_this).after(chunk_html)
    var i = 0
    $("div.chunk").each(function(){$(this).attr('id', "chunk-" + i++)})
    }

</script>

Now, this works, but only for the .chunk that is statically rendered on the page. When I press the button a second chunk appears, but that button does not work. If I add the html for two or more chunks to be rendered, each one works, but the buttons for the chunks it creates do not. What should I do?

Upvotes: 2

Views: 247

Answers (3)

Elangovan
Elangovan

Reputation: 1464

The event handler in the below line attaches the click event to the element matching the selector when you add the handler.

$(".addChunk").click(function(){create_chunk(this.parentNode)})

you can use the live handler to do this. the following code will solve your problem

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

Upvotes: 3

jAndy
jAndy

Reputation: 236142

replace

.bind()

with

.live()

or even better use

.delegate()

which is in your case:

$('#chunk-1').delegate('.addChunk', 'click', function(){create_chunk(this.parentNode);})

furthermore, go to www.jquery.com and read the documentation.

Upvotes: 2

Jerod Venema
Jerod Venema

Reputation: 44642

Use the "live" jQuery function.

$(".addChunk").live('click'. function(){create_chunk(this.parentNode)});

The problem is that you're binding to a single element. The "live" option will monitor the document for any clicks on elements that have the ".addChunk" class.

Upvotes: 2

Related Questions