Variable de Javascript en el nombre del elemento

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?

preguntado el 10 de marzo de 12 a las 09:03

2 Respuestas

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 y $i variables con el var keyword (as in my examples) or they will become global variables.

respondido 10 mar '12, 10:03

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. - Brian

function testScript(fill) {
    choice=document.form1.column.value+'[]';
    for($i=0;$i<fill;$i++){
        document.form1.elements[choice][$i].value=document.form1.copy.value;
    }
}

Actualizado

view sample here: enlace jsfiddle

respondido 11 mar '12, 10:03

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. - Brian

sorry, i have updated the code. I think this is what you needed - diablo rojo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.