ObzidO ObzidO - 1 month ago 9
Javascript Question

Meteor Form getting input value with dynamic name

Taking this form from meteor tutorial as example

<form>
<input type="text" name="playerName">
<input type="submit" value="Add Player">
</form>


I am able to use event.target.playerName.value to access the value of the input.

However if my input name is generated dynamically, how do I access it?


eg. I have playerName1, playerName2, playerName3 and I want to use a for loop to access them.

for (i = 1; i <= 3; i++) {
console.log(event.target.playerName+i.value)
}

Answer

You can refer to object variables using the array notation as well, for example

for (i = 1; i <= 3; i++) {
    console.log(event.target[playerName+i].value)
}