How to know which button was pressed?

北慕城南 提交于 2019-12-05 08:02:47

I think it would be helpful 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' });
});

First of all since you are using POST i am assuming you've got the body-parser middleware present, if not check Body Parser Middleware

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 express

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

req.body.name needs to be req.body.butt

/ needs to be /home2

One trick you can use is to use the two as 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 server side, you should now get value of button_id as 1 or 2, depending on which button was clicked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!