Home > Articles > Programming > JavaScript

Getting Data with Forms Using JavaScript

  • Print
  • + Share This
One of the most popular uses for JavaScript is for working with HTML forms. This lesson includes an overview of the HTML tags to create forms and the corresponding JavaScript objects. It goes on to explain how you can use JavaScript to read data from forms, validate form entries, and send form results by email.
This chapter is from the book

In this hour you'll explore one of the most powerful uses for JavaScript: working with HTML forms. You can use JavaScript to make a form more interactive, validate data the user enters, and enter data based on other data.

This hour covers the following topics:

  • Understanding HTML forms

  • Creating a form

  • Using the form object to work with forms

  • How form elements are represented by JavaScript

  • Getting data from a form

  • Sending form results by email

  • How JavaScript can work with CGI forms

  • Validating a form with JavaScript

The Basics of HTML Forms

Forms are among the most useful features of the HTML language. As you'll learn during this hour, adding JavaScript to forms can make them more interactive and provide a number of useful features. The first step in creating an interactive form is to create the HTML form itself.

Defining a Form

An HTML form begins with the <form> tag. This tag indicates that a form is beginning, and it enables form elements to be used. The <form> tag includes three parameters:

  • NAME is simply a name for the form. You can use forms without giving them names, but you'll need to assign a name to a form in order to easily use it with JavaScript.

  • METHOD is either GET or POST; these are the two ways the data can be sent to the server.

  • ACTION is the CGI script that the form data will be sent to when submitted. You can also use the mailto: action to send the form's results to an email address, as described later in this hour.

For example, here is a <form> tag for a form named Order. This form uses the GET method and sends its data to a CGI script called order.cgi in the same directory as the Web page itself:

<form NAME="Order" METHOD="GET" ACTION="order.cgi">

For a form that will be processed entirely by JavaScript (such as a calculator or interactive game), the METHOD and ACTION attributes are not needed. You can use a simple <form> tag that names the form:

<form NAME="calcform">

The <form> tag is followed by one or more form elements. These are the data fields in the form, such as text fields, buttons, and check boxes. In the next section, you'll learn how JavaScript assigns objects to each of the form elements.

  • + Share This
  • 🔖 Save To Your Account