1

I want to get value from a form: Here's the form:

<form method='post' action='/stack'>
     <input name="stack0" value="stackoverflow0"/>
     <input name="stack1" value="stackoverflow1"/>
     <button type='submit'>Click</button>
</form>

if we want to get the value from the form we use:

app.post('/stack',function(req,res){
     var tmp = req.body.stack0;
     var tmp1 = req.body.stack1;

     console.log(tmp)  // stackoverflow0
     console.log(tmp1)  // stackoverflow1
});

I wont use this method because i have a lot of values, i want something like loop,

for(var i=0;i<2;i++){
    var tmp = req.body.stack(i); // any syntaxe like that ?

    console.log(tmp)  // souldstackoverflow0 if i==0,  souldstackoverflow1 if i==1
}

when i take 0; should tmp take req.body.stack0, and when i==1 tmp = req.body.stack1 ? help plz, and thnx :)

2 Answers 2

4

You have to use the bracket notation to access the object properties if you want to loop over them with a variable in the name:

for(var i=0;i<2;i++){
    var tmp = req.body['stack' + i];

    console.log(tmp) 
}
Sign up to request clarification or add additional context in comments.

Comments

0

We have to use BodyParser to grab data from the input field. Code is here HTML code

 <form class="" action="/" method="post">
 <input type="text" name="newItem" value="" placeholder="Please enter your task">
 <button type="submit" name="button">Add</button>
const express = require('express');

const bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.urlencoded({extended: true}));

var temp = req.body.newItem; console.log(temp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.