How to find out which button is pressed?

I am learning the basics of node.js and express framework. I have a simple page with two buttons:

<form action="/home2" method="post"> <button name="butt1">butt1</button> <button name="butt2">butt2</button> </form> 

And I want to see in the console which button was pressed:

 router.post('/', function(req, res, next) { console.log(req.body.name); res.render('home2', { title: 'post' }); }); 

In the console, I just see

 undefined 

How to access button name?

+5
source share
3 answers

I think that would be useful for you.

 <form action="/home2" method="post"> <button name="butt1">butt1</button> <button name="butt2">butt2</button> </form> router.post('/home2', function(req, res, next) { if(req.body.hasOwnProperty("butt1")){ console.log("butt1 clicked"); }else{ console.log("butt2 clicked"); } res.render('home2', { title: 'post' }); }); 
+2
source

One trick you can use is to use two submit buttons:

 <form action="/home2" method="post"> <button name="button_id" value="1" type="submit">butt1</button> <button name="button_id" value="2" type="submit">butt2</button> </form> 

On the server side, you should now get the button_id value as 1 or 2, depending on which button was clicked.

+1
source

First of all, since you are using POST, I assume that you have existing body-parser middleware if you do not check the "Advanced PC software"

your code needs a few changes

in html

 <form action="/home2" method="post"> <button name="butt" value='1'>butt1</button> <button name="butt" value='2'>butt2</button> </form> 

and in expression

 router.post('/home2', function(req, res, next) { console.log(req.body.butt); res.render('home2', { title: 'post' }); }); 

req.body.name must be req.body.butt

/ should be /home2

+1
source

Source: https://habr.com/ru/post/1235933/


All Articles