Fred
Brack Raleigh, NC |
An HTML form (created via the <form> and other associated tags) is used to collect data from the user of a web page. There is nothing within the HTML language itself which can help with processing any entered data. Typically a web developer would use JavaScript or PHP to receive form data, do something with it, and return a message to the user or alter the output in some manner. A typical message would be that the user's data has been sent on to someone (via email), or an action might be taken such as loading a new web page with or without using user input from the form to affect specifically what is presented on the page.
So creating a form is done via HTML tags, and using the form (known as the form's action) will be done (typically) via JavaScript or PHP.
A form is created via the <form> tag (or element). Other tags are used to display labels for form fields, display buttons, or define "fields" that accept input.
A form field is either text or a selection. Selections can be one of several (a button) or zero or more of several (checkboxes).
Before we show how to create a form field, we should discuss form labels. While you don't need to use the <label> tag, you should! The reason you should use <label> tags is that they aid people who are blind and use screen readers, plus they make it easier to "check" a checkbox without landing your cursor exactly inside the small square. So just do it!
A <label> tag references a single field on a form and contains the text to be associated with the field. If you put the <label> tag ahead of a field tag, the label comes first. If you put it after a field tag, that's where the text goes. If you want the label to appear above a field, you put a <br> tag after the end of the label. Here is the format of the <label> tag by itself. You will see it in context shortly.
<label for="yourname">What is your name?</label>
The for keyword identifies the value of the name keyword in the related form field (as shown below). The body of the tag is the exact text you want for the label, and this may include HTML. One reason you might want to include HTML is to offer extra spacing between your label and an immediately following input field on the same line. One blank is automatically inserted by the browser, assuming the form input tag is on the next line. But in HTML, if you want more than one blank in a row, you need to specify one or more occurrences of the entity. Thus if you wanted three spaces, you need to add an entity to the line like this:
<label for="yourname">What is your name? </label>
Now you have one space from the , one from the blank shown, and one added by the browser. If instead you wanted to put the input field on the next line instead of right after the label, you would code this:
<label for="yourname">What is your name?</label><br>
The components of a form are identified primarily via the <input> tag. An associated type keyword tells us what type of input is expected; for example, a text field versus radio buttons. Oddly, there is one key exception: multiline text input, which has its own keyword.
There are two types of text input fields: single line and multiline. The associated HTML tag names are <input> and, rather strangely, <textarea>. Let's take <input> first.
<input type="text" id="yourname" name="myname">
type="text" tells us what to expect in the input field: plain text. This will present a box on the screen in which the user types his or her answer.
id="yourname" tells us how to identify and distinguish this field within the form. Remember our <label> tag with for="yourname"? That's how we tie the two elements together.
Finally, name="myname" tells us how to name the value the user supplies in this field when we pass the form results along for further processing. In other words, our JavaScript or PHP code will look for a keyword called myname to pickup the user's name. [Often the id and name value are the same. Because this was a name field, we wanted to make the distinctions between the various components more obvious, which is why you see name, yourname, and myname!]
If you need multiple lines for user input (an example would be a free-form comment field), then you use the <textarea> tag instead. It looks like this:
<textarea id="comment" name="comments" rows="3" cols="100">
It needs no type because it is self-defining. id and name are as defined for <input>. rows and cols define the size of the input area.
So let's combine everything we have learned so far. Here is a form with two input fields, followed by its coding (color coded and boxed only for display purposes here):
<form> <label for="yourname">What is your name?</label> <input type="text" id="yourname" name="myname"><br> <label for="comment">Enter your comments:</label><br> <textarea id="comment" name="comments" rows="3" cols="100"> </form>
It may have occurred to you that the form as presented is useless because there is no way to submit it; but before we go there, let's talk about other types of input fields ... or you can jump to Submit now.
A radio button is used when the user is asked to select one and only one option from a list of possibilities. A checkbox is used when the user gets to select zero or more items from a list. They are both options on forms.
<p>Select your gender:</p> <form> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label><br> <input type="radio" id="female" name="gender" value="female"> <label for="female">Female</label><br> <input type="radio" id="other" name="gender" value="other"> <label for="other">It's Complicated...</label> </form>
In this case, the <label> tag appears after the <input> tag because that's where we want the label positioned. Since it appears after, the <br> tag appears at the end of it, not the <input> tag. The id of each <input> tag is different, of course, to allow association with the correct <label> tag; but the name keyword value is identical on each of them, because only one of them can be set. So the correct gender will be returned.
<p>How to you want to be notified? (You may select more than one)</p> <form> <input type="checkbox" id="notify1" name="notifym1" value="Home"> <label for="notify1">Home Phone</label><br> <input type="checkbox" id="notify2" name="notifym2" value="Cell"> <label for="notify2">Cell Phone</label><br> <input type="checkbox" id="notify3" name="notifym3" value="Text2Cell"> <label for="notify3">Via Text to Cell Phone</label> </form>
Unlike radio buttons, for checkboxes each value has to be unique, and therefore they all have to be checked in the action routine.
There actually are numerous type values for the <input> tag. Of note are the following; and if you want to see more, check out the w3schools list of input types.
There are others (like date, time, month, color, email), but they typically have restrictions like not working with Firefox properly, and you won't see them often. You are better off validating input in your action routine.
By including keyword attributes on your <input> statements, you can alter how they act or what input is acceptable. You have already seen several examples above with value, min, max, and step. Others are:
Let's talk now about how to submit a form.
A button to submit a form is simply another type of <input>: we just use a different type keyword: type="submit".
<input type="submit" value="Submit">
In this case, the value keyword identifies the text to appear on the Submit button. You will most likely want to precede your Submit button with a <br>. Adding the break and line above to our previous form results in what follows (though pressing the Submit does nothing except reposition the page to this section):
When you click a button defined with type="submit", one of two things happen:
At this time, we will only discuss the first option.
The action keyword of the <form> tag specifies where the form's data (the keyword/value pairs from the name fields and user input) get sent. Typically this would be the URL of a web page on your website. Thus, for example:
<form action="searchresults.html" method="get">
or
<form action="sendmail.php" method="post">
The method keyword defines how to send the data to the receiving web page.
get
post
It may be an oversimplification, but I suspect that forms handled via JavaScript typically use the get method, where those handled via PHP are more likely to be post. You will have to decide what works best for you.
From our example above, you can deduce two examples of what forms might be used for:
While we haven't talked about how to process a form's data yet, let's take a look at a form which combines some of the options mentioned above. You will note that we have enclosed some sections within paragraph tags. This sort of formatting gives you options like selective font choices, background colors, putting some options in table cells, etc. In other words, formatting the fields in a form allows a lot of flexibility. We haven't even mentioned using STYLEs or CLASSes on the tags, but you can do that, too. We have bolded key items in the sample code.
<p><strong>Enrollment Form</strong>. Fields marked with an * are required!</p> <form> <input type="hidden" name="campaign" value="2021-A"> <label for="name">What is your name?*</label> <input type="text" id="name" name="myname" required><br> <label for="pswd">Choose a password*</label> <input type="password" id="pswd" name="password" required> <input type="button" minlength="8" maxlength="12" value="Rules" onclick="alert('Your password must be 8-12 alphanumeric characters ...')"> <p>Have you ever worked for us before?*<br> <input type="radio" id="yes" name="worked" value="Yes"> <label for="yes">Yes</label><br> <input type="radio" id="no" name="worked" value="No" checked> <label for="no">No</label> </p> <p>How can we get in touch with you?* (You may select more than one)<br> <!-- See Note 1 below about this "required" entry --> <input type="checkbox" id="notify1" name="notifym1" value="Home"> <label for="notify1">Home Phone</label><br> <input type="checkbox" id="notify2" name="notifym2" value="Cell"> <label for="notify2">Cell Phone</label><br> <input type="checkbox" id="notify3" name="notifym3" value="Text2Cell"> <label for="notify3">Via Text to Cell Phone</label> </p> <label for="comment">Enter your comments:</label><br> <!-- See Note 2 below regarding <textarea> --> <textarea id="comment" name="comments" rows="3" cols="100"></textarea><br> <input type="submit" value="Submit Your Form"> <input type="reset" value="Reset All Values"> </form>
Note 1: There is no way in HTML to verify that at least one checkbox is checked. You can mark the field required, but you will have to validate it in your JavaScript or PHP code.
Note 2: If you don't put the </textarea> immediately following <textarea>, you will get one or more leading blanks in your comment.
OK, now you have built your form and specified a URL in the form's action field to process the data. How does that work?!
While there may be other options, the primary ones are to use JavaScript on the action page to read the form's data values and do whatever, or use PHP to do the same. If you use PHP, the filetype of the action page must typically be .php, not .html, and, of course, you must know how to code PHP! This is a mini-tutorial on how to do either.
If you specify method="get" as a form keyword, the values of all the keywords set in your form get passed to the action page as part of the URL. The URL will be suffixed with a question mark, then the keyword-value pairs will follow, with blanks replaced by plus-signs. Example:
URL = http://www.bracksco.com/personal/formaction.html?myname=Fred+Brack&comments=These+are+my+comments.
Using JavaScript, you would access these keyword-value pairs as follows. Sample code is included to show how to detect missing values you expected and translate encoded characters (e.g., %21) and blanks ("+").
var urlParams = new URLSearchParams(window.location.search); var username = urlParams.get("myname"); var comments = urlParams.get("comments"); if (comments==null || comments=="") { --your error handling-- }; // null = "comments=" not present comments = decodeURIComponent(comments); // fix any %nn special characters // The following "regular expression" says replace ALL (g=global) instances of "+" with a blank comments = comments.replace(/\+/g," ");
After that, you are on your own! Feel free to explore our JavaScript tutorials though ...
A particularly popular use of forms would be to collect data from a user and send an email to someone using that data. This is best done with PHP (because it has a built-in mail function). We cover how to do this on a separate page: Using PHP to Send Mail From an HTML Form.
I hope this has been useful. Please send me any comments using the email link below.
Fred