Reputation: 509
I have a text box, and a select box with choices that are the same as the columns in a table. I want to be able to type in the box, select a column, press a button, and have it copy whatever is in the box, to every box in the column. I am having a hard time with the syntax as using a variable is the only thing that prevents this from working. When I put in real values, it works fine.
function testScript(fill) {
choice=document.form1.column.value;
alert (fill);
alert (choice);
for($i=0;$i<fill;$i++){
document.form1.choice[$i].value=document.form1.copy.value;
}
}
Fill (tested by the alert) provides me with the number of rows in the table and works fine. Choice is my select (drop down) box. If I type in "document.form1.make[$1].value= it fills what I type in every row of the make column. If I choose make in the select box, choice does say make as indicated by my test alert.
Any ideas how to use the variable correctly in the for loop?
Upvotes: 1
Views: 4830
Reputation: 1919
function testScript(fill) {
choice=document.form1.column.value+'[]';
for($i=0;$i<fill;$i++){
document.form1.elements[choice][$i].value=document.form1.copy.value;
}
}
Updated
view sample here: jsfiddle link
Upvotes: 0
Reputation: 150020
If I understand you correctly, the syntax you are looking for is:
document.form1[choice][$i].value=document.form1.copy.value;
In a general sense, to access a property "prop1" of an object obj
you can use two syntaxes:
obj.prop1
// or
obj["prop1"]
With the square bracket syntax you can use any expression as long as it evaluates to a string that is the name of the property you want, so:
var x = "prop1";
obj[x]
// or
var x = "pr", y = "op1";
obj[x + y]
...are both going to access the same property as obj.prop1
.
Note also that you should declare your choice
and $i
variables with the var
keyword (as in my examples) or they will become global variables.
Upvotes: 4