Hi I am trying to populate a select statement based on another select statement. In the beginning the select statement with id location is empty and is being populated with an ajax call and its contents replaced. On change I want another select statement called repository to change. I am trying to create a jquery but it is not firing. I know it has to do with event delegation but I tried to fix my code and it is still not working. The replacement is causing this issue.
Any help please?
$.ajax({
'url' : ajaxurl,
data: {
'action':'get_locations', // This is our PHP function below
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$("#location").replaceWith(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
//jQuery(document).on('change', location , function(){
jQuery('#location').on('change', '#location', function() {
window.alert('yep');
$.ajax({
'url' : ajaxurl,
data: {
'action':'test', // This is our PHP function below
},
success:function(data) {
window.alert(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
You are setting a listener on the #location element, but then you replace that element with the content of the ajax response using replaceWith(). Even if the $ajax call comes first in the code, it is asynchronous and the response will arrive after you have set the listener on #location.
The replaceWith() method removes all data and event handlers associated with the removed nodes: https://api.jquery.com/replaceWith/
Also, the change event is fired for <input>, <select>, and <textarea> elements only: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
You could instead use a MutationObserver and observe the parent node of the node you are changing: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver