views:

508

answers:

4

I'm trying to use this code:

var field="myField";
vals[x]=document.myForm.field.value;

In the html code I have

<form name="myForm">
  <input type='radio' name='myField' value='123' /> 123
  <input type='radio' name='myField' value='xyz' /> xyz
</form>

But this gives me the error:

document.myForm.field is undefined

How can I get field to be treated as a variable rather than a field?

+3  A: 

Use the elements[] collection

document.forms['myForm'].elements[field]

elements collection in DOM spec

BTW. If you have two fields with the same name, to get the value of any field, you have to read from:

var value = document.forms['myForm'].elements[field][index_of_field].value

eg.

var value = document.forms['myForm'].elements[field][0].value

and, if you want to get value of selected radio-button you have to check which one is selected

var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
Rafael
+5  A: 

Assuming that your other syntax is correct (I havne't checked), this will do what you want:

var field="myField";
vals[x]=document.myForm[field].value;

In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.

rmeador
You can reach an object's property with the dot notation as well. You only have to use the bracket operator when the property's name is a reserved word or you can't explicit tell the property name.
Török Gábor
+2  A: 

You have to do it like this:

var field = "myField";
vals[x] = document.myForm[field].value;

or even

vals[x] = document.forms.myForm.elements[field].value;
Greg
That worked, however it doesn't give me the value of the radio i had selected, it gives both radios..
Click Upvote
A: 

Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:

var vals = new Array();
$("form[name='myForm'] :radio").each(function() { 
    vals.push($(this).val()); 
});

:-D

KyleFarris