0

here is my problem...

i use ajax and jquery to fill up a form... the user chooses something in a select, and, as he has chosen this or that, ajax returns data, and this data is placed into the form...

sometimes, new elements are created with the ajax data return, example :

ajax returns "blahblah", then i put it in my form, like this :

$("#myDiv").empty();
$("#myDiv").html(ajaxReturn);

IT WORKS FINE! BUT :

the new elements i put into my form are not observed anymore by my jquery...! i have a function like this :

$("#xxxx").on("change",function(){
    alert("something");
});

this function works great for the element i have in my form at PAGE LOAD, once this element is replaced by another coming from my ajax call, EVEN IF it has the same ID as the previous one, the actions on it are no more spotted by JQuery...

how can i solve that?

(i really need to replace my select with my ajax return, because sometimes it's no more a select but an input text i need...)

thanks for advices :)

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
Julo0sS
  • 2,096
  • 5
  • 28
  • 52
  • `$("#myDiv").empty();` this is not required. `.html()` replaces everyting inside. – Jai Jul 11 '14 at 13:15

2 Answers2

2

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

As you are replacing elements using ajax.

You need to use Event Delegation using .on() delegated-events approach.

Use

$("#myDiv").on('change', "#xxxx", function(){
    //Your code
});

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Satpal
  • 132,252
  • 13
  • 159
  • 168
2

Delegate the event to the closest static parent when page was ready:

$("#myDiv").on("change", "#xxxx", function(){
    alert("something");
});

also the first line is not required because it replaces all the innerHTML of this div:

// $("#myDiv").empty(); <----you can remove it.
$("#myDiv").html(ajaxReturn);
Jai
  • 74,255
  • 12
  • 74
  • 103