[thelist] javascript - how to refer to (x)html elements

Joshua Olson joshua at waetech.com
Wed Nov 12 07:38:57 CST 2003


Tim,

So what was does the final version of the code look like?  I'm guessing
something like this:

<form id="myform">
  <input type="text" name="myinput">
</form>

<script>
  form = document.getElementById("myform");
  input = form.elements.myinput;
  alert('The value is ' + input.value);
</script>

Or, are you saying that you can still have the name attribute in the form
tag and still be compliant?

As an aside, I often time find that most of the JS I write that modifies or
examines a form is triggered via the onsubmit handler for the form or
through one of the form's elements.  That being the case the reference to
the form is available immediately without having to go through the document
object.

Example:

<form id="myform" onsubmit="validate(this);">

When the validate function is called at the submittal of the form it's
parameter will now reference the calling form:

function validate(form)
{
  // form already contains a reference to the form, so I can go straight to
the elements.
  input = form.elements.myinput;
  alert('The value is ' + input.value);
}

Likewise, if the script is triggered via a form element, you could do the
following:

<input type="text" name="whatever" id="whatever"
onchange="dosomething(this.form);">

function dosomething(form)
{
  // form already contains a reference to the form, so I can go straight to
the elements.
  input = form.elements.myinput;
  alert('The value is ' + input.value);
}

One other pearl of wisdom:  it's a good idea to go through the elements
collection under the form object.  Here's an example of what I mean:

version 1: form.myinput.value
version 2: form.elements.myinput.value

The reason I recommend using the elements collection is because it
alleviates the problem where a field name matches an attribute name on the
form object.  If you have an element in the form called "name" for example
then the "name" attribute of the form object and it's element with the name
"name" will be in conflict.  Explicitly going through the elements
collection avoids this ambiguity.

If you specifically want to look at the attributes of the form itself you
can use the attributes collection, fyi.

<><><><><><><><><><>
Joshua Olson
Web Application Engineer
WAE Tech Inc.
http://www.waetech.com
706.210.0168



More information about the thelist mailing list