Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  115] [ 4]  / answers: 1 / hits: 21390  / 7 Years ago, fri, july 7, 2017, 12:00:00

i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.



Whenever the onchange event tries to use the function i have defined
filterChanged(), it provides a reference error: filterChanged is not defined
at HTMLSelectElement.onchange



i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.



see below the code -



main.js



var filterChanged = function() {
console.log('filter changed');
}

window.onload = function() {
let filter = document.getElementById('filter-list');
filter.setAttribute('onchange', 'filterChanged()');
}


index.html



<!doctype html>
<html>
<head>
<meta charset=UTF-8>
<title>TestProj</title>
<script type=text/javascript charset=UTF-8 src=build/bundle.js></script>
</head>
<body>
<h3>Todos</h3>
<p>Number of items to show</p>
<select id=filter-list name=filter>
<option selected=true value=list10>10</option>
<option value=list20>20</option>
<option value=list30>30</option>
</select>
<ul id=todo_list>
<!-- Inject list here with JS (main.js getTodos()) -->
</ul>
</body>
</html>

More From » html

 Answers
176

You can use different ways.
First way adding onchange to your select:



<select id=filter-list name=filter onchange=filterChanged();>


Second way using eventListener:



filter.addEventListener('change', filterChanged);


Third way :



window.onload=function() {
let filter = document.getElementById('filter-list');
filter.onchange=function() {
// The code of your function
}
}

[#57176] Thursday, July 6, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrances

Total Points: 184
Total Questions: 100
Total Answers: 92

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;