Binding DropDownList With Database In Node.js

In this article, we will learn how to bind the Drop-Down List from the database in Node.js.

A Drop-Down List is a graphical control element, that allows the user to choose one value from a list. When a Drop-Down List is activated, it displays a list of values, from which the user may select one. When inactive, it displays a single value.

Prerequisites:

  • Basic knowledge of Node.js
  • Code editor like Visual Studio 2019
  • Microsoft SQL Server Management Studio

If you’re new in Node.js? You must have to follow the link given below to set up a new Node.js App in Visual Studio.

How To Create Node.js App In Visual Studio

Bind a DropDownList in Node.js project

Here, we create a StudentInfo table with given fields in the SQL Server.

Firstly, right-click the project name in the Solution Explorer and select Add -> New Folder (Database).

Now, right-click the folder name (Database) in the Solution Explorer and select Add -> New File… (dbConnection.js).

Open the dbConnection.js file and add the code in it.

exports.dbConnection = function () {
    var dbConfig = {
        user: "sa", // SQL Server Login
        password: "thecodehubs", // SQL Server Password
        server: "DESKTOP-78L71550", // SQL Server Server name
        database: "Student" // SQL Server Database name
    };
    return dbConfig;
};

Now, we have to install a package to connect SQL Server.

Install the mssql package with the NPM:

Right-click on the npm from Solution Explorer -> Install New npm Packages…

Search and install mssql package.

Open the index.js file from the routes folder and add the code in it.

'use strict';
var express = require('express');
var router = express.Router();

var _sqlPackage = require("mssql");
var _config = require('../Database/dbConnection');

/* GET home page. */
router.get('/', function (req, res) {

    _sqlPackage.connect(_config.dbConnection()).then(() => {
        return _sqlPackage.query`SELECT * FROM StudentInfo;`
    }).then(result => {
        // Pass the DB result to the template
        res.render('index', { dropdownVals: result.recordset })
    }).catch(err => {
        console.log(err)
    })

});

module.exports = router;

Open the index.html file from the views folder and add the code in it.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>Bind DropDownList</h1>
    <label>Name: </label>
    <select>
        <% for (const i in dropdownVals) { %>
            <option value="<%= dropdownVals[i].ID %>"> <%= dropdownVals[i].Name %> </option>
        <% } %>
    </select>
</body>
</html>

Output:

 

Also, check How To Prevent Copy Content Using JavaScript

7 Comments

  1. Priyanka

    Hi, i want to fetch tables from database in drop down list, in nodejs .
    When we select drop down it shows tables name from my database .
    But I don’t know how to implement this task .
    Can u please help me

    Reply
  2. litala

    Hi, couldn’t manage to get it working because I am missing app.js file. Kindly provide me with app.js file. Thanks.

    Reply
    1. litala

      I got it working with this app.js

      ‘use strict’;
      const express = require(‘express’);
      const path = require(‘path’);// add path module,
      const cors = require(‘cors’);
      const bodyParser = require(‘body-parser’);
      const engine = require(‘consolidate’);

      const app = express();

      //app.set(‘port’, (process.env.PORT || 5000));
      //app.use(express.static(__dirname + ‘/public’));
      // view engine setup
      app.set(‘views’, __dirname+ ‘/views’);
      // make server object that contain port property and the value for our server.
      //app.engine(‘html’, engine.mustache);
      app.engine(‘html’, require(‘ejs’).renderFile);
      app.set(‘view engine’, ‘html’);

      // routers
      const apiRouter = require(‘./routes/index’);

      // use the modules
      app.use(cors());
      app.use(bodyParser.json());
      app.use(express.json())
      app.use(express.urlencoded({extended: true})) // parsing incoming requests with urlencoded based body-parser

      // use router
      app.use(‘/’, apiRouter);
      // router user input
      app.get(‘*’, function(req, res){
      res.render(‘index.html’);
      });

      const server = {
      port: 4040
      };

      // starting the server
      app.listen(server.port, () => console.log(`Server started, listening port: ${server.port}`));

      Reply
  3. Indranil Chatterjee

    I have one question how can i do the same thing(Binding DropDownList With Database In Node.js) with MySql database and handlebars template.

    Reply
    1. Fabian Yate

      Same

      Reply
    2. komal

      IN Route:

      router.get(“/”, (req, res) => {
      brandModel.find({}, (err, docs) => {
      if (!err) {
      res.render(“../views/admin/”, { brands: docs })
      } else {
      console.log(err);
      res.render(“../views/admin/”)
      }
      }).lean();
      })

      In UI:

      Select Brand:

      — Select Brand —
      {{#each brands}}
      {{this.brandName}}
      {{/each}}

      Note:Here we used mongodb Model

      Reply
    3. Renato Freire Correia

      works with you? i have the same doubt

      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories