0

I have a Jquery function that when a button add_entry is clicked, inserts a 'save button' inside the page like this; the button shows up, so I assume that part is working.

 $("#add_entry").click(function(){
    $("#add_entry").hide();
    $('#status').append(<button class="save_entry">Test</button>);
});

then I have yet another function that is supposed to be called when aforementioned save button is clicked:

 $(".save_entry").click(function(){
    alert("i dont work :/");
});

which makes me wonder...

a) How does DOM manipulation actually work? - Since the jquery part is wrapped into the $document.ready() method does that mean i cant access 'on-the-fly' created elements like that ?

b) when injecting elements with DOM manipulation, they never appear in the source... why?

Thank you for your time.

aashima
  • 1,203
  • 12
  • 31
  • Duplicate of lots of others [like this](http://stackoverflow.com/questions/31119535/element-not-detecting-click-event/31119601#31119601) – area28 Jun 29 '15 at 16:31

1 Answers1

1

For dynamically added elements, you need to bind events like following.

$(document).on("click", ".save_entry", function(){
    alert("i will work now");
});

As suggested by Rory, you can also bind the event to #status.

$("#status").on("click", ".save_entry", function(){
    alert("i will work now");
});

For reference - http://api.jquery.com/on/

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59