Basically the function below empties out the select field and re-populates it with the updated options when there are changes in the chrome.storage.local. This is also when I want to add on event listeners to the options, so that I can implement custom actions.
But I'm at my wits end on this, for some reason I cannot add an event listener to the options. I have a setTimeout function that prints out the options after they're rendered, and the options are there but the onclick is null. I've also tried adding on event listeners with a setTimeout to double check if they were being overwritten in another step, but that didn't work either.
Edited to clarify from feedback: Console does not show the event listener callback console.log('working'), therefore it's not working. And I'm already using a select onchange listener. But I need to re-focus to the 'info' field, even if they re-select the same option.
Any help would be greatly appreciated!
function updateSelectOptions(selectID){
var selectList = document.getElementById(selectID);
while (selectList.length > 0) {
selectList.remove(selectList.length -1);
}
var storage = chrome.storage.local;
storage.get(['settingsArray', 'selectedPage'], function(data) {
var settingsArray = data.settingsArray;
var settingsNameArray = settingsArray.map(function(ele) {
return ele.pageName;
});
if (selectID === 'pageSelectDropdown') {
settingsNameArray.push('Add New Page');
}
var selectedPage = data.selectedPage;
//Create and append the options
for (var i = 0; i < settingsNameArray.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", i);
option.setAttribute("class", 'optionClass');
option.text = settingsNameArray[i];
option.addEventListener('click', ()=>{
console.log('working')
document.getElementById('info').focus();
});
selectList.appendChild(option);
}
document.getElementById(selectID).value = selectedPage;
})
}
Actually even this toy example doesn't work, what's wrong here? Mouseup, click neither produces the console.log event.
<select id='pageSelectDropdown'>
<option value='Add New Page'>Add New Page</option>
<option value='Great Page'>Great Page</option>
<option value='Family Page'>Family Page</option>
</select>
<script type="text/javascript">
opts = document.getElementsByTagName('option');
console.log(opts)
for (i = 0; i < opts.length; i++) {
opts[i].addEventListener('click', ()=>{
console.log('clicked')
})
}
</script>
but the onclick is null
adding an event listener usingaddEventListener
does not change an event listener that is "added" using.onclick =
- so it's perfectly fine that.onclick
is null - the event listener should have been added correctly regardless – Jaromanda XselectList.options.length = 0
. – RobG