PDA

View Full Version : generic function syntax for form


Chris P
10-28-2005, 02:04 PM
Hello
I am trying to learn/write a function that will automatically get the form membership of an element and print out the index of that element. From here (http://www.mattkruse.com/javascript/tabnext/source.html) I have this code:
function getElementIndex(obj) {
var theform = obj.form;
document.getElementById("elementIndex").value=obj.form; //show form
for (var i=0; i<theform.elements.length; i++) {
if (obj.id == theform.elements[i].id) {
return i;
}
}
return -1;
}

My problem is that If I pass this an element the code never captures the form. That diagnostic show form line just prints [object HTMLForm] and not the form of the element. What is the correct syntax to pass a function a form element and have the function extract the form and use it in the script? tia.

Pyth007
10-28-2005, 08:16 PM
I'm somewhat confused as to what you are trying to do... What type of element is elementIndex and why are you trying to pass an object (the form in this case) to the element's value? If you are trying to insert a form into a <div> (or some other html tag) then you would have to use:
document.getElementById("elementIndex").appendChild(theForm);
(or maybe document.getElementById("elementIndex").innerHTML=theForm; would work? not sure on this one...)

Otherwise if elementIndex is a text-box or text-area, their values can only hold strings (or "[object]" if you try to pass it an object). Did you mean to pass the form's name / id? If so, then use:
document.getElementById("elementIndex").value=theForm.name;

Or were you wanting to see what the element's index was that was passed into the function (this is what the original script was written for)? Then just before the line "return i;" have:
document.getElementById("elementIndex").value=i;

Maybe if you could more broadly explain what you are wanting to do, I can help some more...

Kor
10-31-2005, 10:03 AM
function that will automatically get the form membership of an element and print out the index of that element.


Simply:

getElementIndex(obj) {
var allElements = obj.form.elements;
for(var i=0;i<allElements.length;i++){
if(obj==allElements[i]){var elIndex=i};break
}
alert(elIndex)
}