Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  146] [ 5]  / answers: 1 / hits: 16451  / 9 Years ago, sat, april 11, 2015, 12:00:00

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 :)


More From » node.js

 Answers
23

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

[#67107] Thursday, April 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilianoc

Total Points: 568
Total Questions: 109
Total Answers: 99

Location: Oman
Member since Sat, Jan 7, 2023
1 Year ago
;