[thelist] detecting form fields in JS

jeff jeff at members.evolt.org
Mon Dec 11 02:28:49 CST 2000


matthew,

:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: From: Matthew Walker
:
: How do I detect whether or not a form element exists?
:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

a form is an object as is a form element.  so, all you have to do is some
object detection.

if(document.forms[0]) document.forms[0].elements[0].focus();

or

if(document.forms[0].elements[0]) document.forms[0].elements[0].focus();

however, this may not be enough to prevent an error.  you see, if you try to
focus an element that can't take focus then you'll cause an error.  elements
that can't take focus are hidden form fields, disabled form fields, and form
fields whose display style is set to none or visibility set to hidden.

i've done some testing and can't find a way to test this without a long
complicated conditional.  i was hoping to be able to simply check if the
object supported the focus() method like this:

if(document.forms[0].elements[0] &&
   document.forms[0].elements[0].focus)
   document.forms[0].elements[0].focus()

however, this doesn't work as expected.  so, that leaves us with checking to
make that the form element is not a hidden element, not disabled, doesn't
have it's display style set to none, and doesn't have it's visibility set to
hidden.   so, keeping all of this in mind, here goes:

if(document.forms[0].elements[0] &&
   document.forms[0].elements[0].type != 'hidden' &&
   document.forms[0].elements[0].disabled != true &&
   document.forms[0].elements[0].style.display != 'none' &&
   document.forms[0].elements[0].style.visibility != 'hidden')
   document.forms[0].elements[0].focus();

this may not cover all the situations though and it would only work in ie4+.
you'll still get an error in the instance where the form is contained in a
<div> who's visibility is set to hidden or display is set to none.  as you
can see this can get quite complicated.

if possible, i would suggest moving this element focus out of the body tag
and into somewhere else in your document where you can control alittle
better what documents it appears in.

good luck,

.jeff

name://jeff.howden
game://web.development
http://www.evolt.org/
mailto:jeff at members.evolt.org





More information about the thelist mailing list