How to parse a variable in Javascript

I am trying to use this code:

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

      

In the html code i

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

      

But this gives me an error:

document.myForm.field is undefined

      

How can I get field

to be treated as a variable and not a field?

+1


source to share


4 answers


Assuming your other syntax is correct (I haven't tested it), this will do what you want:

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

      



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

+7


source


Use collection items []

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

      

collection of elements in the DOM specification

BTW. If you have two fields with the same name, in order to get the value of either field, you should read:

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 the value of the selected radio button you need 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;

      

+3


source


You should do it like this:

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

      

or even

vals[x] = document.forms.myForm.elements[field].value;

      

+2


source


Based on your tags, it looks like you are using jQuery. If so, you can simply do this and it will make your life a lot easier:

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

      

: - D

0


source







All Articles