My question is: How do I reference a dynamic 'name' of an input element in a form?
For instance, with the following HTML:
<form>
<input type="text" name="qty1" value="input1" />
<input type="text" name="qty2" value="input2" />
<input type="text" name="qty3" value="input3" />
<input type="submit" value="Submit" onClick="checkVal(this.form); return false;" />
</form>
Javascript:
function checkVal(form) {
for (var i = 1; i <= 3; i++) {
alert(form.qty+i.value); // Here's where my problem is..
}
}
The above javascript does not work. The alert is outputting NaN
.
How do I reference qty1
, qty2
, and qty3
in a for loop using i
variable?
Here's a jsfiddle: /
My question is: How do I reference a dynamic 'name' of an input element in a form?
For instance, with the following HTML:
<form>
<input type="text" name="qty1" value="input1" />
<input type="text" name="qty2" value="input2" />
<input type="text" name="qty3" value="input3" />
<input type="submit" value="Submit" onClick="checkVal(this.form); return false;" />
</form>
Javascript:
function checkVal(form) {
for (var i = 1; i <= 3; i++) {
alert(form.qty+i.value); // Here's where my problem is..
}
}
The above javascript does not work. The alert is outputting NaN
.
How do I reference qty1
, qty2
, and qty3
in a for loop using i
variable?
Here's a jsfiddle: http://jsfiddle.net/MRzWf/
Share Improve this question edited Jan 31, 2020 at 0:30 Bryan Elliott asked Feb 14, 2014 at 18:41 Bryan ElliottBryan Elliott 4,0952 gold badges23 silver badges23 bronze badges 1- alert(document.getelementbyid('qty' + i).value); – user3272686 Commented Feb 14, 2014 at 18:44
5 Answers
Reset to default 10Use Bracket notation
form["qty" + i].value
function checkVal(form) {
for (var i = 1; i <= 3; i++) {
console.log("qty" + i, form["qty" + i].value);
}
}
<form>
<input type="text" name="qty1" value="input1" />
<br/>
<input type="text" name="qty2" value="input2" />
<br/>
<input type="text" name="qty3" value="input3" />
<br/>
<input type="submit" value="Submit" onClick="checkVal(this.form); return false;" />
</form>
Simply login as a dictionary
http://jsfiddle.net/MRzWf/2/
alert(form["qty"+i].value);
Problem is form.qty+i
,
To access the element of array you should used index
inside the parenthesis.
There is another way to check value of input. Here is one.
function checkVal(form) {
var allInputs = document.getElementsByTagName('input');
for (var i = 0; i < 3; i++) {
if(allInputs[i].type == 'text'){
alert(allInputs[i].value);
}
}
}
DEMO
Standard Solution
Using: form.elements[]
should work in all browsers..
function checkVal(form) {
for (var i = 1; i <= 3; i++) {
alert(form.elements["qty"+i].value);
/* OR using dynamic name variable
var ename = "qty"+i;
alert(form.elements[ename].value);
*/
}
}
Try this. It works for the above problem
function checkVal(form) {
for (var i = 0; i < 3; i++) {
alert(document.getElementsByTagName("input")[i].value);
} }