Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Displaying Data from a Form

As a simple example of using forms, Listing 12.1 shows a form with name, address, and phone number fields, as well as a JavaScript function that displays the data from the form in a pop-up window.

Listing 12.1 A form that displays data in a pop-up window

<html>
<head>
<title>Form Example</title>
<script LANGUAGE="JavaScript" type="text/javascript">
function display() {
  DispWin = window.open('','NewWin', 'toolbar=no,status=no,width=300,height=200')
  message = "<ul><li><b>NAME: </b>" + document.form1.yourname.value;
  message += "<li><b>ADDRESS: </b>" + document.form1.address.value;
  message += "<li><b>PHONE: </b>" + document.form1.phone.value + "</ul>";
  DispWin.document.write(message);
}
</script>
</head>
<body>
<h1>Form Example</h1>
Enter the following information. When you press the Display button,
the data you entered will be displayed in a pop-up window.
<form name="form1">
<p><b>Name:</b> <input TYPE="TEXT" SIZE="20" NAME="yourname">
</p>
<p><b>Address:</b> <input TYPE="TEXT" SIZE="30" NAME="address">
</p>
<p><b>Phone: </b> <input TYPE="TEXT" SIZE="15" NAME="phone">
</p>
<p><input TYPE="BUTTON" VALUE="Display" onClick="display();"></p>
</form>
</body>
</html>

Here is a breakdown of how this HTML document and script work:

  • The <script> section in the document's header defines a function called display that opens a new window (as described in Hour 11) and displays the information from the form.

  • The <form> tag begins the form. Because this form is handled entirely by JavaScript, no form action or method is needed.

  • The <input> tags define the form's three fields: yourname, address, and phone. The last <input> tag defines the Display button, which is set to run the display function.

TIP

As usual, you can download the listings for this chapter from this book's Web site: http://www.jsworkshop.com/.

Figure 12.1 shows this form in action. The Display button has been pressed, and the pop-up window shows the results.

Figure 12.1. Displaying data from a form in a pop-up window.

  • + Share This
  • 🔖 Save To Your Account