I have a Node.js application consisting of the following file system:
public
elegant-aero.css
stadium-wallpaper.jpg
team-results.html
public.js
app.js
teamresults.mustache
Through an HTML form, I want to populate the options of a dropdown menu based on the user's selected option from another dropdown menu. HTML is below:
<form>
<label for="selectLeague">
<span>National League:</span>
<select id="selectLeague" name="leagueCode">
<option style="display:none;"></option>
<option value="SP1">Spanish La Liga</option>
<option value="E0">English Premier League</option>
<option value="D1">German Bundesliga</option>
<option value="F1">French Ligue 1</option>
<option value="I1">Italian Serie A</option>
<option value="P1">Portuguese Primeira Liga</option>
<option value="N1">Dutch Eredivisie</option>
<option value="SC0">Scottish Premier League</option>
</select>
</label>
<label for="selectTeam">
<span>Team Name:</span>
<select id="selectTeam" name="teamName">
<option>Choose a team:</option>
<!-- populated after user makes a selection on league -->
</select>
</label>
<label>
<span></span> <input type="submit" value="Submit">
</label>
</form>
There are simple ways that this can be accomplished with just JavaScript through client-side rendering. For example: Dynamically Populating Drop down list from selection of another drop down value
However, I absolutely cannot get this to work with Node.js (sever-side). Following the example in the link above, I created a JavaScript file called public.js and put it in the public directory. The JavaScript file contains the following dummy code:
// Hard code all teams by their leagues, as a test
const teamsByLeague = {
SP1: [
"Real Madrid",
"Barcelona"
],
E0: [
"Chelsea",
"Arsenal"
]
}
function updateTeamSelection(leagueCode) {
if (leagueCode.length == 0) document.getElementById("selectTeam").innerHTML = "<option></option>";
else {
var teamOptions = "";
for (teamIndex in teamsByLeague[leagueCode]) {
teamOptions += "<option>" + teamsByLeague[leagueCode][teamIndex] + "</option>";
}
document.getElementById("selectTeam").innerHTML = teamOptions;
}
}
I updated the HTML file to contain this line on the league selection dropdown menu:
<label for="selectLeague" onChange="updateTeamSelection(this.value);">
And added this in the body of the HTML document:
<script src="public.js"></script>
And lastly, following an advice I saw in the following StackOverflow page:
nodejs/express include local js file
I added the following line to app.js:
app.get('/public.js',function(req,res){
res.sendFile('public.js');
});
Nevertheless, after all of this, when changing the selection on the league dropdown menu, I still get the error message:
Uncaught ReferenceError: updateTeamSelection is not defined onchange
Not exactly sure what am I missing. Any help is massively appreciated!