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.
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
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.
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:
Our Dedicated Programmers for Hire can ensure that your mobile app or website has a secure, reliable, and sound backend. To ensure smooth operation, the backend developers are well-versed in building correct, high-quality, and sophisticated scripts. Hire backend developers in India on flexible engagement and pricing structures, and collaborate with them in your time zone. Bring your website or mobile app to life with a solid backend built by our backend engineers utilizing the most up-to-date technology while maintaining security.
Also, check How To Prevent Copy Content Using JavaScript
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
View Comments
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
im searching for the exact same.... if you found it plz give the link
Hi, couldn't manage to get it working because I am missing app.js file. Kindly provide me with app.js file. Thanks.
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}`));
I have one question how can i do the same thing(Binding DropDownList With Database In Node.js) with MySql database and handlebars template.
works with you? i have the same doubt
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
Same