-1

I am trying to add a click event to an element that I appended through jQuery. If I have the item in my HTML code the click event works fine. I hope the code explains it better

HTML

<div id="addNew">Add new Item</div>
<div id="priceWrapper"></div>
<div class="price"></div>

JS

var data;
$('#addNew').click(function () {
    $('#priceWrapper').append('<div class="item" data-js="2.5" id="Item" >(I dont work i was not here on load)I AM AN ITEM WICH COSTS 2.5€</div>');
});
$('#Item').click(function () {
    data = $(this).attr("data-js");
    alert(data);
});

Example in JsFiddle

Thanks for your help

Sukanya1991
  • 760
  • 3
  • 16

1 Answers1

0

Use jQuery .on. More information here

var data;
$('#addNew').click(function (e) {
    e.preventDefault();
    $('#priceWrapper').append('<div class="item" data-js="2.5" id="Item" style="background-color:yellow;border-bottom:solid 5px green">(I dont work i was not here on load)I AM AN ITEM WICH COSTS 2.5€</div>');
});

$('body').on('click', '.item', function () {
    data = $(this).attr("data-js");
    alert(data);
});

Fiddle


The reason this doesn't work is because first of all, only one element can have an id at a time. We have to set it to use the class .item. The other problem is the event is getting set when the page loads so it doesn't notice the new items.

Downgoat
  • 11,422
  • 5
  • 37
  • 64