Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to get form elements by using form name in javascript

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>
like image 578
bassnoodle Avatar asked Oct 13 '10 19:10

bassnoodle


People also ask

How do we access the elements of a form using form object in JavaScript?

The Form Object in HTML DOM is used to represent the HTML < form > element. This tag is used to set or get the properties of < form > element. This element can be accessed by using getElementById() method.

How do you reference a form in JavaScript?

In order to access a form through JavaScript, we need to obtain a reference to the form object. One obvious way to approach, is to use the getElementById method. For instance, if we had a form with the id attribute "subscribe_frm" , we could access the form in this way: var oForm = document.

Can be used to find all form elements in HTML document?

elements. The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the <form> element. Independently, you can obtain just the number of form controls using the length property.


1 Answers

Technically what you have should work ok... 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 failures in IE as it will auto-reference the form element, not the value you are trying to extract.

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

like image 177
scunliffe Avatar answered Oct 02 '22 13:10

scunliffe