views:

40

answers:

4

I want to grab a form object from an external javascript function instead of passing it from a submit button inside the tags.

So for example lets say my form is:

<form id="form1">
 //inputs...
</form>

Normally I would just put a button in there with onClick="submitFunction(this.form)" to pass it to my javascript function, however now I'd like to be able to grab all that form data from an external function, but obviously "this.form" doesn't work outside the form tags.

There's probably a simple way to do this I am overlooking?

Thanks

+3  A: 

Use getElementById

function submitForm(){
    your_form = document.getElementById('form1');
}
Bang Dao
this works perfectly, thanks
Then please accept this answer
Bang Dao
A: 

And there comes power of jQuery...

$('#form1') ...

$('#form1 input') ...

$('#form1').submit(function() { $(this)... }

Māris Kiseļovs
i think he is looking for javascript
Pranay Rana
The sheer power of loading kilobytes of JS in order to cut two thirds of the typing needed to get document.getElementById(). It really isn't worth it unless you are doing relatively significant things with JS and want to refactor at least a large chunk of it to use jQuery.
David Dorward
@June R: jQuery **is** JavaScript.
David Dorward
A: 
submitFunction(document.getElementById("form1"))
jtbandes
A: 

You can use getElementsByTagName() to retrieve all the elements in the document that have a specific tag name. Here's an example HTML file:

<html>
    <head>
        <script src="MyFile.js" type="text/javascript"></script>
    </head>
    <body>
        <input id="Item1" name="Item1" type="text" />
        <p>
            <input id="Item2" name="Item2" type="text" />
        </p>
        <form name="MyForm">
            <input id="Item3" name="Item3" type="text" />
            <input id="Submit" type="button" value="Submit"/>
        </form>
    </body>
</html>

And here's what MyFile.js would look like:

document.getElementById("Submit").onclick = function()
{
    var Items = document.getElementsByTagName("input");
    for (var i = 0; i < Items.length; i++)
    {
        // Do something useful here.
        alert(Items[i].value);
    }
}

The above example would alert four times (Item1, Item2, Item3, and Submit). You could check Items[i].id to ignore the Submit input.

Zach Rattner
The question is looking to grab a form element which has an id.
David Dorward