Accessing Text Fields


window.alert(f.elements["textfield"].value); 

HTML supports three types of text fields:

  • Single-line text fields: <input type="text" />

  • Multiline text fields: <textarea></textarea>

  • Password fields: <input type="password" />

Although: these fields behave quite differently in a web browser, access from JavaScript is quite similar. The value attribute of each of these fields contains the text within the field. This can be used both for reading and for writing the field's text.

The following code shows two things: first, how to access the field's property, and second, how to use this.form to give easy access to the field's form.

Accessing a Text Field (textfield.html)

<script language="JavaScript"   type="text/javascript"> function showText(f) {   window.alert(f.elements["textfield"].value); } </script> <form>   <input type="text" name="textfield" />   <input type="button" value="Show text"     onclick="showText(this.form);" /> </form> 

Figure 8.1 shows what happens if a user enters some text in the field and then clicks on the button.

Figure 8.1. The text appears after the button is clicked.


Note

This approachusing the value property to access the data in the form fieldalso works for hidden fields (<input type="hidden" />).





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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