I'm working on a form, with selects created dynamically. So I did this:
function populateSelect() {
$.ajax({
type: "GET",
url: URLSELECT + 'tipologia',
success: function (response) {
let key;
for (var k in response._embedded) {
key=k;
break
}
createSelect(response._embedded[key], "tipologia")
let options = $('select[name=tipologia]').find('option');
options.each((el)=>{
$(this).on('click', function(){
console.log($(this));
})
})
},
error: function(err){
console.log(err);
}
});
}
function createSelect(options, select) {
options.forEach((el)=>{
let text = el.name;
let option = document.createElement('option');
option.setAttribute('value', text);
option.textContent = text
option.addEventListener('click', function(e){
console.log('test);
})
document.querySelector(`[name=${select}]`).appendChild(option);
})
}
Now if I inspect the HTML the option are created in right way, with the right value and right text, but the addEventListener is not working.
Firstly, the
click
event is not well supported onoption
elements. The far better practice is to listen for thechange
event on the parentselect
, then read the value of the chosenoption
.Also, your code is a lot more complex than it needs to be. You can more easily build the list of
option
elements from the response of the AJAX request usingmap()
andappend()
. Try this: