Access form in document.forms without knowing index or name:

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Access form in document.forms without knowing index or name:

Post by shortaug »

Suppose I have a form that has no name and no id and I wish to access all of its elements by calling documents.form[].elements[].

From what I can tell, I would have to use this.form so that my function would know fromm which object it is being called.

The problem now however: I am not calling that function from the form, but rather from another function that accepts the 'this' as a parameter.

IE:

Code: Select all

 
 
function anotherFunction(form, group) {
    var buttons = document.forms[form].elements[group];
}    
 
function someFunction(form) {
    anotherFunction(form, "group")
}
 
<form onsubmit="return someFunction(this);" action="..." method="get">...other stuff in here...</form>
 
 
So, how in anotherFunction would I know which is my index to use in document.forms[]? Or, is it even possible?
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Re: Access form in document.forms without knowing index or name:

Post by JAB Creations »

Give the form an id, it's required for the label element which you are using correct?

Code: Select all

<div><label for="my_id">name</label><input id="my_id" name="my_name" type="text" value="" /></div>
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Re: Access form in document.forms without knowing index or name:

Post by shortaug »

Nope, in this sense, it's an anonymous form and has to remain as such.

Not a single identifier outside of the elements themselves.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Access form in document.forms without knowing index or name:

Post by kaszu »

Code: Select all

function anotherFunction(form, group) {
    //'form' variable references to actual FORM element, so you don't need to use document.forms[...]
    var buttons = form.elements[group];
}
Nope, in this sense, it's an anonymous form and has to remain as such.
Why?

Form is an element in DOM, so it's not anonymous, you can get that form at any moment by calling

Code: Select all

var form = document.getElementsByTagName('FORM')[0]; //or whatever index it has
shortaug
Forum Newbie
Posts: 13
Joined: Wed May 13, 2009 6:11 pm

Re: Access form in document.forms without knowing index or name:

Post by shortaug »

lol, duh. thanks Kaszu.

It's anonymous in the sense that I've nothing by which I can identify it outside of 'this' and I have no idea what the potential index might be.

just using 'form.elements[group]' works. I should have realized why...
Post Reply