JQuery - selection of dynamically created divs

I have a quick jQuery question:

First, my HTML:

<div id="taskinput">
    <form>
         <input id="taskinput-box" type="text"></input>
         <input type="submit"></input>
    </form>
</div><!-- end taskinput -->
<div id="taskoutput"></div><!-- end taskoutput -->

I am creating content in #taskoutput from a user using .append when creating a new .task class.

$("#taskinput").submit(function() {
    var tasktext = $('#taskinput-box').val()
    $('#taskoutput').append('<div class="task">'+tasktext+'</div>');
    $('#taskinput-box').val("");
    return false;
});

The above code is working fine; The problem occurs when I try to select created divs. The following code does not work:

$(".task").click(function() {
    $(this).slideUp();
});

What am I missing?

+3
source share
4 answers

You should use delegate eventboth with on:

$('#taskoutput').on('click', '.task', function(){
    $(this).slideUp();    
});

@salek DEMO , buton

Read the ondocs :

; , .on(). , , , HTML . HTML-, , HTML . , .

, -, . , , , , , . Model-View-Controller, , , . HTML-, , .

+2

$(".task").click(... " .task , , . , , .

, . - , .task click #taskoutput. jQuery on :

$('#taskoutput').on('click', '.task', function(){
    $(this).slideUp();    
});
+2

jquery .on() HTML, . :

$("#taskoutput").on({
    click: function() { $(this).slideUp(); }
}, '.task');
0

, , - live ('click', function() {...

jsfiddle http://jsfiddle.net/2ZmF4/

$(".task").die().live('click', function() {
    $(this).slideUp();
    return false;
});​

you will need to decide whether you need a call to die depending on your scenario ... I still have it there ...

0
source

All Articles