Reputation: 1987
I try to attach event handler for dynamic element but failed.
Here's some of my code. I want event can be called by dynamic element. Maybe javascript provide function to support attach event for dynamic element automatically without bind it again such as jQuery live or on method. I want to add functionality to load city data while state or province selected to Magento Sales > Order > Create New Order Page without have to search a correct javascript file and try to bind event on it again.
window.addEventListener('load', function(){ function getCity(){ id= this.selectedIndex; name= this.name; getKota(id, name); } billing_address_region_id= document.getElementsByName('order[billing_address][region_id]'); shipping_address_region_id= document.getElementsByName('order[shipping_address][region_id]'); var event = new Event('change'); billing_address_region_id[0].addEventListener('change', getCity, false); shipping_address_region_id[0].addEventListener('change', getCity, false); billing_address_region_id[0].dispatchEvent(event); shipping_address_region_id[0].dispatchEvent(event); });
Thanks a ton
Upvotes: 0
Views: 1070
Reputation: 388316
Note: This solution is not tested.
What you could do since the target elements are added dynamically is to register a change event handler to the window
, then see whether any of the target element fired the change event if so do your action.
window.addEventListener('change', function (e) {
var el = e.target;
if (el.name == 'order[billing_address][region_id]' || el.name == 'order[shipping_address][region_id]') {
getKota(el.selectedIndex, el.name);
}
});
Upvotes: 1
Reputation: 221
Your code would work only for already existing elements. I recommend using jQuery.
Using jQuery, you can use "on" method.
$('#elem').on('change', function(){
// Do stuff
});
Upvotes: 0