Reputation: 541
I have two select-boxes, each of them is in span element with specific id. The first select-box is country, the other one is city list. When I select a country the innerHtml of city select-box container span is replaced by response of ajax function everything is good. But I want to fire a function by useing onchange attribute of selectbox if at the begining of page loading addeventListener function works fine but affter replacement of innerHtml of span it does not work and after replacement the id of city selecbox is same es before replacement. I am just using.
document.getElementById('to_city').addEventListener('change',doSomething,false);
this code is initialized by onload of window element.
It works without ajax replacement but dont after.
Upvotes: 1
Views: 5039
Reputation: 9090
When you replace contents with AJAX you need to bind event again. so its good idea to bind event again after replacing content.
There is a way to avoid it using event bubbling.
JQuery 1.4+ supports onchange event propagation so you can use jquery delegate function to achieve same. http://api.jquery.com/delegate/
with Jquery only one line do the work.
$("#container").delegate("#to_city", "change", doSomething); // Workd in all browsers
I ignored IE in below example as you are using addEventListener which is not supported by IE. Without Jquery Working example (Not working in IE) : http://codebins.com/bin/4ldqpb1/2
document.getElementById("container").addEventListener( 'change', function(e) {
var targ=e.target;
if (targ.id == "to_city") { //you just want to capture to_city event
//DO STUFF FOR SELECT
//DO STUFF
doSomething();
alert("id: " + targ.id + "\nvalue: " + targ.value);
}
}, false)
Explanation:
When you bind any events they are bound to that particular element not the selector or ID. so when you replace the content and new replace element with the new element with the same ID, new element doesnt have any event attached. so you need to attache event again. so if you attach event after AJAX content replace doSomething will work. but that is not a very good solution.
We are using event bubbling concepts. many events are bubbled to the top of the document. (IE doesn't bubble change event) So we write handler on the container and listen for the event. each event has a target or srcElement which says which dom element firing this event. if the dom element is what we are looking for execute function. in this can we are looking for element with ID to_city that's why if condition.
Upvotes: 1