Forms are a really important aspect of HTML. It is through the use of Forms that we can accomplish interactivity and data collection from the user. There are many different ways to implement forms and the various form elements that go along with them when you are creating your web pages or web applications. This episode will take a close look at the ones you are most likely to be using or maintaining in your various projects. Let’s jump right in to the wonderful world of HTML Forms!
The HTML <form> Tag
We can get this party started with the The HTML <form> Tag, for without it, none of the other elements we will soon discuss are going to have much meaning for you! HTML Forms are typically used to send data to a server side technology like PHP for processing. You can also use JavaScript to process form data in the client, and that is becoming quite popular as well. The HTML <form> Tag is a container of sorts so that you can place elements like Radio Buttons, Text Areas, Input fields and more for data collection inside of it. The syntax looks like so:
<form>
<-- place input elements in between the form tags -->
</form>
We would take a look at how this renders in the browser, but the form itself is actually not displayed in the browser. It is only the elements within the form that display, and we’ll take a look at some of them now.
<input type="text">
Text fields for input are used to give the user a one line field to enter text. They are quite common, and this is an example of the syntax to create one.
<form>
Website: <input type="text" name="website"><br>
Computer: <input type="text" name="computer">
</form>
This HTML renders in the browser like so
You’ll notice the name
attribute in the source code here. This is a very important attribute! It is by this attribute that you can access data collected to the form in your server side code. You will see exactly how this works shortly.
<input type="password">
An input can also have a type of password
. This input essentially works the same as type text
, but the browser will obscure the input text by making the characters you type invisible by turning them into small circles or asterisks. In addition, when you submit the form, the browser will usually ask you if you would like to have your password remembered. This is all due to setting the type to password
. This is some HTML that denotes an input with it’s type set to password
.
<form>
Password: <input type="password" name="password">
</form>
This is how it displays in the browser.
<input type="checkbox">
The checkbox seems simple enough. Then you learn about Radio Buttons 🙂 There is sometimes some confusion between the two, since they both look pretty similar in the browser with the exception that checkboxes come in the shape of a small box, while radio buttons look more like a small circle. Each of them share the trait of being able to be selected by the user. They seem so alike, so what gives?! The main idea is that checkboxes are used for one or many choices. Say you provided a list of four seasons to the user. With the checkbox option, the user could select just one, or all of the seasons. With the radio button option, the user would only be able to select her favorite. The HTML looks like this.
<form>
<input type="checkbox" name="season" value="spring"> Spring<br>
<input type="checkbox" name="season" value="summer"> Summer<br>
<input type="checkbox" name="season" value="fall"> Fall<br>
<input type="checkbox" name="season" value="winter"> Winter
</form>
This HTML displays in the browser like so.
<input type="radio">
Now that you see how checkboxes work, it is the perfect time to observe how Radio Buttons work! Like we explained above, a collection of checkboxes provides the user the ability to select one or many options. The radio button is different in that the user can only select one. We can redo the above HTML and simply change the type to radio. Observe.
<form>
<input type="radio" name="season" value="spring"> Spring<br>
<input type="radio" name="season" value="summer"> Summer<br>
<input type="radio" name="season" value="fall"> Fall<br>
<input type="radio" name="season" value="winter"> Winter
</form>
This HTML displays in the browser like so.
To hammer the point home, try to select all of the seasons in both scenarios above. What was the result?
<textarea>
We now get into some HTML form elements that are their own being, that is to say they do not have a type! All of the examples above are of various inputs, and what determines how they work is the type
that they are assigned. The <textarea> tag is the first such one we’ll take a look at. The <textarea> tag is used to provide a larger surface area to place text into than the one line <input type="text"> provides. <textarea> has attributes of both rows
and cols
so that you can specify the size of the <textarea> Let’s take a look.
<form>
<textarea rows="5">
This is a beautiful textarea, provided courtesy of http://www.vegibit.com. Type away in here and see how I work.
</textarea>
</form>
<select>
The <select> tag is used to provide a drop down list to the user. Inside of the <select> tag, you place <option> tags to contain each different possible selection. The <select> tag is a single choice selection scenario by default. You can change this to a multiple selection by adding []
brackets to the end of the name
attribute and setting the multiple attribute. You can hold down the Ctrl in windows and the Command button on a Mac in order to select more than one option.
<form>
<select name="select2[]" multiple="multiple">
<option>Chinese</option>
<option>Mexican</option>
<option>Italian</option>
<option>Thai</option>
<option>Seafood</option>
<option>Indian</option>
<option>Mediterranean</option>
</select>
</form>
<datalist>
The <datalist> tag is pretty slick in that it provides a type of auto complete functionality as the user begins to type. The auto completion is done by checking what the user types against all of the values provided for each option. The closest match will auto populate when the user begins typing. The list
attribute of the associated input element is what binds the datalist
and input
together.
<input name="days" list="days">
<datalist id="days">
<option value="Sunday">
<option value="Monday">
<option value="Tuesday">
<option value="Wednesday">
<option value="Thursday">
<option value="Friday">
<option value="Saturday">
</datalist>
<input type="submit">
The Mac Daddy, The Big KaHuna, The Stud to rule them all – it is our trusty <input type="submit"> button. At the completion of your form, you are going to need a way to actually take all of the collected data and send it on over to the server for some processing. You do this of course with the Submit Button. When the user clicks the Submit Button in your form, the data which was collected will be sent to a specific server side page based on the action
attribute which was set in the opening <form> tag. This data can be passed via GET
or POST
. We’re focusing on POST
in this episode. There are countless ways to style the submit button, but the actual HTML to enable this to happen looks something like this:
<form name="input" action="process.php" method="post">
Website: <input type="text" name="website">
<input type="submit" value="Submit">
</form>
Create Your HTML Form
Now that we have covered several important features of HTML Forms, we can go ahead and build one as an example for collecting data. Let’s go ahead and build a form that will put all of these concepts to use. First we’ll use an <input type="text"> to capture an email address. Then we’ll insert a couple of <input type="checkbox"> to show how checkboxes work. After that, we’ll add a nice <textarea> to show how you can have a multi-line area for typing text. Next comes a dropdown menu by way of the <select> tag so the user can choose the best basketball player of all time. Once this is done, we’ll need to allow the user to choose their favorite foods using the <select multiple> tag. Before we submit, we’ll provide one last option to chose the best day of the week and use the <datalist> to give some auto complete magic as well. Here is the code to do it!
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Using HTML Forms For Data Collection</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
<script src="jquery-1.11.1.js"></script>
<script>
$(document).on('submit', 'form.form-horizontal', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: jQuery('form').serialize(),
success: function (data) {
jQuery('#results').append(data);
},
error: function (xhr, err) {
alert('Error');
}
});
return false;
});
</script>
</head>
<body class="container">
<div id="form">
<h2> Using HTML Forms For Data Collection <small>Any element you want to collect data from in a form must have a name property. The name becomes the key name of the associative array once the form is submitted.</small></h2>
<form class="form-horizontal" action="print_r_post.php" method="post">
<fieldset>
<div class="form-group">
<div class="col-xs-12">
<input name="textinput1" class="form-control" id="inputEmail" placeholder="Email" type="text">
<span><strong><input></strong> of type text</span>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input name="textinput2" pwfprops="," class="form-control" id="inputPassword" placeholder="Password" type="password">
<span><strong><input></strong> of type password</span>
<div class="checkbox">
<input name="checkbox1" type="checkbox">
<span><strong><input></strong> of type checkbox</span>
</div>
<div class="checkbox">
<input name="checkbox2" type="checkbox">
<span><strong><input></strong> of type checkbox</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<textarea name="textarea" class="form-control" rows="3" id="textArea"></textarea>
<span><strong><textarea></strong> is not an <strong><input></strong> and has no type</span>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="radio">
<input name="radioOptions" id="optionsRadios1" value="option1" type="radio">
<span><strong><input></strong> of type radio</span>
</div>
<div class="radio">
<input name="radioOptions" id="optionsRadios2" value="option2" type="radio">
<span><strong><input></strong> of type radio</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<select name="select1" class="form-control">
<option>Jordan</option>
<option>James</option>
<option>Bird</option>
</select>
<strong><select></strong> is not an <strong><input></strong> and has no type
<br>
<select name="select2[]" multiple="" class="form-control">
<option>Chinese</option>
<option>Mexican</option>
<option>Italian</option>
<option>Thai</option>
<option>Seafood</option>
<option>Indian</option>
<option>Mediterranean</option>
</select>
<strong><select></strong> with the multiple attribute allows multi selections
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input name="days" class="form-control" list="days">
<datalist id="days">
<option value="Sunday">
<option value="Monday">
<option value="Tuesday">
<option value="Wednesday">
<option value="Thursday">
<option value="Friday">
<option value="Saturday">
</datalist>
<strong><datalist></strong> provides autocomplete as you begin typing
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="bg-info" id="results"></div>
</body>
</html>
print_r_post.php
<pre class="bg-info">
<h3>
<?php
print_r($_POST);
?>
This is an example of Rick James filling out all of the information in our form. Dealing with the server side processing of all of this data is beyond the scope of this episode, but a good thing to include here is an example of being able to view the raw data that gets submitted. We use just a small piece of JavaScript to do this by sending the data via AJAX to the print_r_post.php file on the server using jQuery. This PHP file does nothing more than to print recursively all of the data that gets sent to it. That data then gets inserted into the page, again using jQuery. The code to make it happen is right here.
$(document).on('submit', 'form.form-horizontal', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: jQuery('form').serialize(),
success: function (data) {
jQuery('#results').append(data);
},
error: function (xhr, err) {
alert('Error');
}
});
return false;
});
You can run this code in your own local development environment as well. The output when we click the submit button here should result in the following getting inserted into the page.
Awesome! Being able to dump this form data to an array makes it easy to troubleshoot and debug any form problems you may run across during your web development adventures 🙂
As an added bonus, now that you are a pro in creating awesome forms in HTML, you can also read up on PHP Form Processing so that you can do whatever you like with the data you are able to collect!