1

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I believe you understood me correctly, however I had already tried your suggestion and unfortunately it doesn't work. I'm not sure what else to try.
0
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

2 Comments

I tried your suggestion, but it doesn't work. I've tried many other variations as well. Do you think I need a different approach to the problem or are you sure this is possible. It seems like the best way, but I'm sure.
sorry, i have updated the code. I think this is what you needed

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.