无法通过在JavaScript中使用表单名称来获取表单元素

问题描述:

我在通过名称访问我的表单时遇到问题。当我使用document.form [0] .mylink.value时,它会识别值并输出到我指定的innerHTML。但是,当我使用document.myform.mylink.value时,它似乎无法识别表单。我已经在Chrome 6.0和FireFox 3.6.3中尝试了这一点,并获得相同的结果。我真的需要能够通过使用表单名称(而不是document.form [0])访问我的表单值,为什么document.myform.mylink.value不起作用的任何想法?

I am having an issue with accessing my form by it's name. When I use document.form[0].mylink.value it recognizes the value and outputs to the innerHTML that I specify. However, when I use document.myform.mylink.value it doesn't seem to recognize the form. I have tried this in chrome 6.0 and also firefox 3.6.3 and get the same result in both. I really need to be able to access my form values by using the form name (instead of document.form[0]), any ideas why document.myform.mylink.value doesn't work?

<form name="myform">
<table>
<tr><td valign="middle" align="center">
    <div id="textResponse"></div>
</td></tr>
<tr><td height="30" valign="middle" align="center">
    <input name="mylink" value="Enter a URL" size="31" />
</td></tr>
<tr><td valign="top" align="center">
    <a href="javascript:submitForm2();">Click</a>
</td></tr>
</table>
</form>

<script type="text/javascript">
function submitForm2(){
    //This one does NOT work:
    my_link = document.myform.mylink.value;
    //This one also does NOT work:
    //my_link = document.forms['myform'].mylink.value;
    //This one works:
    //my_link = document.forms[0].mylink.value;

    document.getElementById("textResponse").innerHTML="<p>"+my_link+"</p>";
}
</script>


下面的完整语法也应该可以工作:

Technically what you have should work ok... the full syntax below should also work:

var my_link = document.forms['myform'].elements['mylink'].value;

如果偶然,您的真实代码中的变量是mylink not my_link您将在IE中失败,因为它会自动引用表单元素,而不是值您试图提取。

If by chance your variable in your "real" code is "mylink" not "my_link" you will get failures in IE as it will auto-reference the form element, not the value you are trying to extract.

这就是说,您的代码发布 ... 在Firefox / IE中运行良好(此处演示: http://jsfiddle.net/Ymg8W/

That all said, your code as posted... works just fine in Firefox/IE (demo here: http://jsfiddle.net/Ymg8W/ )