Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected option value in node.js with using express

I need to get the selected object using express to console it in app.js

example.html

 <form id="tableForm" action="getJson">
        <select class="example" name="example">
              <option name="" value="0" selected>Select table</option>
              <option name="table1" value="1">Table 1</option>
              <option name="table2" value="2">Table 2</option>
              <option name="table3" value="3">Table 3</option>
        </select>
    </form>

App.js

var express = require('express'),
app = express();

app.use(express.bodyParser());

 app.get('/', function(req, res){
  res.sendfile('views/index.html');
});

app.get('/getJson', function (req, res) {
   console.log(req.body.example);
});

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
});

The output of the console is undefined even if I select another object.

like image 593
shiva Avatar asked Sep 05 '25 10:09

shiva


1 Answers

You need to add handler for the post method on form submission.

app.js

app.post('/getJson', function (req, res) {
   console.log(req.body.example);
});

example.html

<form method="post" id="tableForm" action="getJson">
  <select class="example" name="example">
      <option name="" value="0" selected>Select table</option>
      <option name="table1" value="1">Table 1</option>
      <option name="table2" value="2">Table 2</option>
      <option name="table3" value="3">Table 3</option>
  </select>
</form>
like image 56
Sridhar Avatar answered Sep 08 '25 16:09

Sridhar