¿Es esto posible: document.form.array [i] .value?

I have not found an answer to this online nor does the debugger tell me enough to understand what alternatives I might use. Is it possible to post the "fill" value into the text boxes using an array to the effect I'm trying to use below? I could write document.form.a.value = fill; document.form.b.value = fill; etc., but a loop and array seems more more simplified and efficient. Here's a simplified version of the code that's giving me an error:

<script type="text/javascript">
function postData() {
var fill = 0.0;
var txtBoxLetter = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    for (var i = 0; i < txtBoxLetter.length; i++)   {
        document.form.txtBoxLetter[i].value = fill; // Error on this line
    }
}
</script>

<form name="form" method="" action="">
<input type="text" name="a" size="1" readonly="true">
<input type="text" name="b" size="1" readonly="true">
<input type="text" name="c" size="1" readonly="true">
<input type="text" name="d" size="1" readonly="true">
<input type="text" name="e" size="1" readonly="true">
<input type="text" name="f" size="1" readonly="true">
<input type="text" name="g" size="1" readonly="true">
<input type="text" name="h" size="1" readonly="true">
// etc.
</form>

Gracias por la ayuda!

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

2 Respuestas

MDN form elements

document.form.elements[ txtBoxLetter[i] ].value = fill;

respondido 10 mar '12, 01:03

Exactly the syntax I needed. Thank you! - Modular

Use square brackets to use a variable as a property name...

document.forms[0][txtBoxLetter[i]].value = fill;

It's the same thing you're doing when you do...

txtBoxLetter[i]

If you actually have a-z, you could skip the Array...

for (var i = 0; i < 26; i++)   {
    document.forms[0][String.fromCharCode(i + 97)].value = fill;
}

respondido 10 mar '12, 02:03

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