I'm using Express with Handlebars for front-end. When the selected option in the dropdown in home.handlebars
changes, I want to trigger an event and read the value of the selected option in index.js
. As I understand, I should use a Handlebars helper for this. I created a helper server.js
(the Node.js backend) and added it to the onchange
event for the dropdown. However, the handler does not seem to work. Here is my code:
server.js
:
const express = require('express');
const app = express();
const handlebars = require('express-handlebars');
const port = 3000;
app.use(express.static('public'));
var handlebarsHelpers = handlebars.create({
helpers: {
dropdownChange: function (value) {
console.log("helper running.");
console.log("value is " + value);
return value;
}
}
});
app.engine('handlebars', handlebarsHelpers.engine);
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home', {layout: false});
});
<...>
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
});
index.js
:
import * as d3 from "https://cdn.skypack.dev/d3@7";
import axios from 'https://cdn.skypack.dev/axios';
const dataSet = async function getData() {
return await axios.get('/data');
}
var courseData = [];
function getNodes() {
//************************getNodes is the function that should eventually read the dropdown value************************
}
async function drawGraph() {
const data = await dataSet();
console.log(data);
courseData = data.data;
console.log(courseData);
}
drawGraph();
home.handlebars
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Graph Chart</title>
</head>
<body>
<h2 align="center">Graph Chart</h2>
<div>
<select name="select" id="select" onchange={{dropdownChange value}}>
<option value="">Select a course...</option>
<option value="course1">course1</option>
<option value="course2">course2</option>
</select>
</div>
<svg class="prereq-graph"></svg>
</body>
</html>
<script type="module" src="./static/js/index.js"></script>
How do I fix the issue of the Handlebars helper not working? Alternatively, are there other ways to pass the dropdown selected value from Handlebars to Express when the onchange
event is triggered?
Thank you.
Nevermind, I remembered that Javascript's addListener
is a thing and solved my issue 🙃