Ali
Ali

Reputation: 267227

How to parse a variable in Javascript

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?

Upvotes: 1

Views: 3642

Answers (4)

KyleFarris
KyleFarris

Reputation: 17548

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

Upvotes: 0

Rafael
Rafael

Reputation: 18522

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;

Upvotes: 3

Greg
Greg

Reputation: 321786

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;

Upvotes: 2

rmeador
rmeador

Reputation: 25694

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.

Upvotes: 7

Related Questions