Failed to get form elements using form name in javascript

I am having a problem accessing my form by name. When I use document.form [0] .mylink.value, it recognizes the value and outputs to innerHTML that I specify. However, when I use document.myform.mylink.value, it does not seem to recognize the form. I tried this in chrome 6.0 as well as firefox 3.6.3 and got the same result in both. I really need to have access to my form values ​​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> 
+7
javascript forms
source share
1 answer

Technically, what should work fine for you ... the full syntax below should also work:

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

If by chance your variable in your "real" code is "mylink" not "my_link" , you will get crashes in IE because it will automatically refer to the form element and not to the value you are trying to retrieve.

That says it all, your code as published ... works fine in Firefox / IE (demo here: http://jsfiddle.net/Ymg8W/ )

+18
source share

All Articles