Using Forms


When you add HTML controls to a web page, they should be in a form, which you create with the <FORM> element. Forms are only HTML constructs. They have no visual representation by themselves (unless you use the <FIELDSET> element; see the discussion on that element at the end of this chapter). We've been using forms since Chapter 1, "Essential JavaScript," as in this example where I've placed an HTML button control into a form; and when the user clicks it, JavaScript calls the alerter method to display an alert box.

(Listing 01-03.html on the web site):
 <HTML>      <HEAD>          <TITLE>              Executing Scripts in Response to User Action          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function alerter()   {   window.alert("You clicked the button!")   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Executing Scripts in Response to User Action</H1>          <FORM>  <INPUT TYPE="BUTTON" ONCLICK="alerter()" VALUE="Click Me!">  </FORM>      </BODY>  </HTML> 

So how do you get access to the controls in a form from JavaScript? If you give a form a name using the NAME (not ID ) HTML attribute, you can access those controls using syntax like this, as we've seen earlier:

 document.form1.button1.value = "Clicked!" 

In this case, I'm setting the value property of a button named button1 in a form named form1. That's one way of accessing a control in a form from your codeas document. formName.controlName . You also can use the document object's forms array, which enables you to access forms by number or name. Here's an example where the code changes the caption of a button from Click Me! to You clicked the button! when the user clicks that button (note that the forms array isn't available before version 6 in the Netscape Navigator):

(Listing 12-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Executing Scripts in Response to User Action          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function alerter()              {  document.forms[0].text1.value = ("You clicked the button!")  }              // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Executing Scripts in Response to User Action</H1>          <FORM>              <INPUT TYPE="BUTTON" ONCLICK="alerter()" VALUE="Click Me!">              <INPUT TYPE="TEXT" ID="text1" VALUE="">          </FORM>      </BODY>  </HTML> 

You also can use the form's elements array to access the elements in a form; see "Using Radio Buttons" in this chapter for an example. (You also can still access the controls in a form using the getElementById method and other methods , of course.)



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net