views:

38

answers:

1

Is it possible to append something to a div that was already appended? I tried but nothing happens.. (I'm not using linebreaks in the actual js)

$(document).ready(function() {

    $('.add_text_input').click(function() {
        $('li').append('<div class="input_label">Untitled</div>\
                        <div class="edit_label"></div>\
                        <input type="text" name="untitled" /><br />');
    });

    $('.input_label').click(function() {    
        var input_label = $(this).html();   
        $(this).hide();
        $('.edit_label').append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
    });

});

The js is for creating text inputs and editing their labels. When clicking on the "input_label" div, it should hide using hide() and append a text input with the default "untitled" value in the "edit_label" div. It works if the divs already exist but I need to make it work via append.

Does anyone have any ideas please?

+1  A: 

You just need to use a .live() handler here, like this:

$('.input_label').live('click', function() {
  var input_label = $(this).html();   
  $(this).hide().next('.edit_label')
    .append('<input type="text" name="untitled" value="' + input_label + '"/><br />');
}); 

This will work on elements regardless of when they're created, since it works off event bubbling, it'll work on any element's click event that matches the .input_label selector.

Currently with .click() it's finding all the elements that exist at document.ready time and binding to those elements, not to the selector, so it won't work for dynamically added elements.

Nick Craver
It works! I'm happy that it was simple :) thanks!
Cyber Junkie