Page 1 of 1

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

Posted: Thu Dec 10, 2009 7:18 pm
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?

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

Posted: Thu Dec 10, 2009 10:04 pm
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>

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

Posted: Fri Dec 11, 2009 1:19 am
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.

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

Posted: Fri Dec 11, 2009 11:30 am
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

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

Posted: Fri Dec 11, 2009 12:54 pm
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...