Dynamically Populating Dropdown List with Express, MySql, Node

Issue

I have a simple app that I am building with a friend. We want to take make a dropdown multiselect to have a list that is populated from our DB.

I can get the results no problem, and log them in the console just fine, but I am not able to get the results to pop in the dropdown list.

I’ve added the code below. The app just shows a blank dropdown list, which looks like the size of the returned values, I just can’t tell.

enter image description here

Thanks!

server.js

const express = require('express');
//const ejs = require('ejs');
let mysql = require('mysql2');
let app = express();

let conn = mysql.createConnection({
    host: '***',
    user: '***',
    password: '***',
    database: 'symptom_list'
})

let sql = `SELECT field1 FROM SymptomList`;
let symptoms = [];


app.use(express.static('public'));
app.use(express.urlencoded({
    extended: true
})
);

app.set('view engine', 'ejs');

app.listen(8000);

app.get('/', function (req, res) {
    conn.query(sql, (error, results, fields) => {
        if(error) {  return console.error(error.message) };
            for (let i = 0; i < results.length; i++){
                symptoms.push(results[i].field1);
                console.log(symptoms);
            }
        //console.log(results);
        //symptoms.push(results);
        res.render('pages/index', { dropVals: symptoms[0] });
    });
});

index.ejs

<div>
    <label>Symptoms</label>
    <select>
        <% for (let i=0; i < dropVals.length; i++) { %>
            <option> <% dropVals[i] %></option>
        <% } %>
    </select>
</div>

Solution

you need to use <%= tags to output value into the HTML:

try changing

    <option> <% dropVals[i] %></option>

to

    <option> <%= dropVals[i] %></option>

Answered By – traynor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published