Javascript Form How to - Use the forms array to access a form element








Question

We would like to know how to use the forms array to access a form element.

Answer


<!--from   w w  w  .java  2  s  .  c om-->
    <html>
    <body>
    <script language = "JavaScript">
    function showFormName(){
         var name = document.forms[0].name;
         console.log("The name of the form is: " + name);
    }
    </script>
    <form name="form1">
    This text box belongs to a form.
    <input type="text" name="street">
    <br><br>
    Click on the button to get the name of the form.
    <br>
    <input type="button" value="Get Form name" onClick='showFormName()'>
    </form>
    <form name="form2">
    This is the second form in the document. It contains a FileUpload object.
    <input type="file" name="uploadbox" size="25">
    </form>
    </body>
    </html>

The code above is rendered as follows: