4 methods to get a form

Discussion in 'JavaScript' started by winterheat, Aug 17, 2008.

  1. #1
    there seems to be 4 methods to get a form that is in HTML.

    the ones I have are:

    <script>
    onload = function() {
        document.getElementById("form1").firstname.value = "haha";
        document.forms["form2"].firstname.value = "heehee";
        document.forms[2].firstname.value = "hoohoo";
        document.form4.firstname.value = "wah ha";
    }
    </script>
    
    <form id="form1">
        <input name="firstname" type="text">
    </form>
    
    <form id="form2">
        <input name="firstname" type="text">
    </form>
    
    <form id="form3">
        <input name="firstname" type="text">
    </form>
    
    <form name="form4">
        <input name="firstname" type="text">
    </form>
    HTML:
    a test run is on http://www.0011.com/test_js/test_get_form.html

    they seem to all work in IE 6, 7, Firefox 2, 3, and Safari 3. Are they all good ways of getting a form? It seems that forms[2] may not be so good since what if somebody adds a form in front and then forms[2] will no longer be forms[2] any more. Thanks!
     
    winterheat, Aug 17, 2008 IP
  2. iRakic

    iRakic Member

    Messages:
    40
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #2
    Thanks for sharing this.
     
    iRakic, Aug 17, 2008 IP
  3. blueribbon

    blueribbon Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The newer versions of the browsers work with all those methods, but to support older browsers consider using a function like this:

    function returnObjById( id )
    {
    if (document.getElementById)
    var returnVar = document.getElementById(id);
    else if (document.all)
    var returnVar = document.all[id];
    else if (document.layers)
    var returnVar = document.layers[id];
    return returnVar;
    }

    This way it checks which method is available in the browser, i.e. use returnObjById("form1")
     
    blueribbon, Aug 18, 2008 IP
  4. Stomme poes

    Stomme poes Peon

    Messages:
    3,195
    Likes Received:
    136
    Best Answers:
    0
    Trophy Points:
    0
    #4
    blueribbon's right, IE needs document.all cause it's a tard.

    Also, none of the forms are valid, so the actual script would be more complicated (forms cannot have inlines as direct children).
     
    Stomme poes, Aug 22, 2008 IP