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

Jeff Howden jeff at jeffhowden.com
Wed Nov 12 18:56:13 CST 2003


tim,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Tim Burgan
>
> function collectInfo()
> {
>   var formNr = 0;
>   var elementName = "myName";
>   var element = document.forms[formNr].elements[elementName];
>   alert("The value is " + element.value);
> }
>
> [snip]
>
> <form action="" method="">
>   <input type="text" name="myName" />
>   <input type="button" value="submit"
>          onclick="collectInfo();" />
> </form>
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

you can take this a step further.  you don't even need to know the number of
the form in the forms array.  just pass an object reference.  additionally,
lose the onclick event handler on the input button and move the
collectInfo() function call to the onsubmit event handler of the <form> tag:

<form action="" method="get"
      onsubmit="collectInfo(this.form)">

then, with some slight changes to your collectInfo() function, you're done:

function collectInfo(oForm)
{
  var elementName = 'myName';
  var oElement = oForm.elements[elementName];
  alert('The value is ' + oElement.value);
}

.jeff

——————————————————————————————————————————————————————
Jeff Howden - Web Application Specialist
Résumé - http://jeffhowden.com/about/resume/
Code Library - http://evolt.jeffhowden.com/jeff/code/



More information about the thelist mailing list