how to get value selected in dropdown menu from ejs template to server side node
First, assuming you want to have distinct month_year
values in rows
(CMIIW), I'd suggest you to change the SQL query to reduce complexity in the view:
SELECT DISTINCT month_year FROM attendance_details ORDER BY month_year ASC
Then you can use this to generate your form:
<form id="tableForm" action="/salary-sheet" method="post">
<select class="selectpicker" data-style="btn-info" name="selectpicker">
<optgroup label="Select Table">
<option value="">Select Month Year</option>
<% rows.forEach(function(row){ %>
<option value="<%= row %>"><%= row %></option>
<% }) %>
</optgroup>
</select>
<input type="submit" value="Submit" />
</form>
and process it in the server side:
var express = require('express'),
bodyParser = require('body-parser'),
app = express()
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({
extended: true
}))
app.post('/salary-sheet',function(req,res){
var month = req.body.selectpicker
console.log('month is', month)
res.send(month)
})
app.listen(5000)
faraz
Updated on June 23, 2022Comments
-
faraz almost 2 years
What I want to do is to let the user select monthyear i.e something like feb2017 from a drop down menu and then get the value selected in to server side, where I'll be using the selection to search database where month_year = feb2017, month_year is a column in my database table.
But, for now I just want to get the option selected to the server side. I am using node js , express as well as body parser.
so, how do I go about it?
here's my ejs file
<!DOCTYPE HTML> <html> <head> <title>Add/Edit DA</title> <link rel="stylesheet" href="style.css"> </head> <body> <% var rows %> <% var rowsLength = rows.length %> <div> <form id="tableForm" action="/salary-sheet" method="post"> <select class="selectpicker" data-style="btn-info" name="selectpicker"> <optgroup label="Select Table"> <option name="" value="0">Select Month Year</option> <% for(var i=0;i<rowsLength;i++){ %> <% if(i>0){ %> <% if(rows[i].month_year !== rows[i-1].month_year){ %> <option name="table<%=i %>" value="month1"><%= rows[i].month_year %></option> <% } %> <% }else{ %> <option name="table<%=i %>" value="month2"> <%= rows[i].month_year %></option> <% } %> <% } %> </optgroup> </select> <input type="submit" /> </form> Go back to home page - <a href="/">click here</a> </div> </body> </html>
and here's the related server side.
app.get('/select-month',function(req,res){ connection.query('SELECT month_year FROM attendance_details',function(err,rows){ if(err){ throw err; }else{ var rowsLength = rows.length; console.log('rows is ',rows); res.render('select-month.ejs',{rows:rows}); } }); }); app.post('/salary-sheet',function(req,res){ var month = req.body.table8; console.log('month is ',month); res.send(month); });
would love to know how to get the option selected from ejs to server side