0

I have the below code which works until i try dynamically adding more to the DOM. It should allow for rooms to be added, and then allow for items to be added to those rooms. If you try the online version you'll see the hardcoded html one works as planned, but dynamically added ones with append don't. I have tried .live() but it didnt work for me, i may have used it wrong however

$(document).ready(function () {
    $('.addItem').on('click', function () {
        $('<input type="text"/>').appendTo($(this).siblings('.items'));
    });

    $('#addRoom').on('click', function () {
        var number = 1;
        number++;
        $('<div class="formHolder">\
        <form class="items" rel="' + number + '">\
        <input type="text"/>\
        </form>\
        <div class="addItem">Add Item</div>\
        </div>').appendTo('#content');
    });
});

http://jsfiddle.net/andyjh07/pxdFj/

Andy Holmes
  • 7,817
  • 10
  • 50
  • 83
  • oops! that is meant to be a class haha – Andy Holmes Sep 16 '13 at 08:50
  • you should search before asking question already answered thousand times, and/or use your browser console and ask specific question... – A. Wolff Sep 16 '13 at 08:51
  • possible duplicate of [jQuery .live() vs .on() method for adding a click event after loading dynamic html](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht) – A. Wolff Sep 16 '13 at 08:52
  • i've already tried .live which is what has been suggested on previous questions. I have searched online but things i tried haven't worked. Apologies for a duplicate question but help is needed – Andy Holmes Sep 16 '13 at 08:52
  • 1
    @AndyHolmes live() is removed from jq 1.9, use .on() with delegation syntax. What about reading link provided??? – A. Wolff Sep 16 '13 at 08:54
  • I've only just seen your link, i was replying to your statement before. Thanks for the link – Andy Holmes Sep 16 '13 at 08:56

2 Answers2

1

Use jQuery eventDelegation:

Demo

    $(document.body).on('click','.addItem', function () {
        $('<input type="text"/>').appendTo($(this).siblings('.items'));
    });

    $(document.body).on('click','#addRoom', function () { 
        var number = 1;
        number++;
        $('<div id="formHolder">\
        <form class="items" rel="' + number + '">\
        <input type="text"/>\
        </form>\
        <div class="addItem">Add Item</div>\
        </div>').appendTo('#content');
    });

You can take the closest parent element instead the document.body :)

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68
0

try this

DEMO

 $(document).on('click','.addItem', function () {
    $('<input type="text"/>').appendTo($(this).siblings('.items'));
});
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53