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
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 to share