最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to parse a variable in Javascript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked May 5, 2009 at 15:06 AliAli 267k269 gold badges592 silver badges786 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

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.

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;

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;

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

发布评论

评论列表(0)

  1. 暂无评论