How to redirect a page using JS, based on the value of a <select>
element
I want to replace a load of onchange=""
inline JS actions attached to HTML elements. For example, I have a <select>
that fires an inline onchange=""
event that takes the selected option and redirects using window.document.location.href='
'. I want something that passes CSP rules (no inline scripting) and uses .addEventListener
. This is what I came up with. It works, but looks clunky. Is there a better way ?
window.addEventListener("DOMContentLoaded",EventListeners);
function EventListeners() {
document.getElementById("MySelect").addEventListener("change", ChangeSomething);
}
function ChangeSomething() {
var sel = document.getElementById("MySelect");
var sel_opt = sel.options[sel.selectedIndex].id;
window.document.location.href='page.php?id=' + sel_opt;
}
For some reason, if I try :
document.getElementById("MySelect").addEventListener("change", ChangeSomething);
as the first line, I get an error, saying getElementById(...) is null.