Reputation: 394
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.
Upvotes: 0
Views: 65
Reputation: 337590
Firstly, the click
event is not well supported on option
elements. The far better practice is to listen for the change
event on the parent select
, then read the value of the chosen option
.
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 using map()
and append()
. Try this:
let $select = $('select[name=tipologia]').on('change', e => {
console.log(e.target.value);
});
function populateSelect() {
$.ajax({
type: "GET",
url: URLSELECT + 'tipologia',
success: function(response) {
let options = response._embedded.map(o => `<option value="${o.name}">${o.name}</option>`);
$select.html(options);
},
error: function(err) {
console.log(err);
}
});
}
Upvotes: 2