How to know which button was pressed?

不问归期 提交于 2019-12-07 01:56:52

问题


I'm 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 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 can I access the name of the button?


回答1:


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' });
});



回答2:


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




回答3:


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.




回答4:


I know this is a very old question, but I had the same one and I found a way better solution so I thought I'd share it. You can add different formaction's to different buttons, and do different things with the action in your app. Example:

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

And then on the backend:

app.post("/wigglebutt", (req, res) => {

});

app.post("/slapbutt", (req, res) => {

});


来源:https://stackoverflow.com/questions/33703145/how-to-know-which-button-was-pressed

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