HTML Section 8: HTML forms

HTML Form Elements - The Form Tags


HTML forms are a way of gathering data from visitors to your page. Forms typically have text boxes for data input, radio buttons, drop down boxes, and buttons so that users can submit the form. A reset button is also handy, just in case mistakes are made filling out the form.
For this section, create a new web page in your text editor. Save the file as forms.html. We'll add the different form elements as we go along.

The Form Tag

You don't have to tell your browser about any form elements on your web page. If you just want a simple form element like a text box, you can insert the text box tag by itself. But if you want to do something with the information on your form, like send it somewhere or to someone, you have to "tell" your browser about the form elements on your page. You do this with the Form tag:
<FORM>
</FORM>
Like most HTML tags, the FORM tag comes as a pair, the forward slash preceding the second FORM tag to indicate that the form tag ends. Any form elements you need then go between these two FORM tags.
A NAME attribute is a useful addition to the FORM tag. When the form has a name, you can then refer to it in scripts.
<FORM NAME = "frmTest">
</FORM>
To give your form a name, type a space after FORM then type the word NAME, followed by an equals sign. Finally, add a name for your form. You can call it anything you like. Here, we've called the form frmTest.
If you want your form to go somewhere or to someone, two other attributes are needed in the FORM tag: METHOD and ACTION. Like this:
<FORM NAME = "frmTest" METHOD = "post" Action ="mailto:me@me.com">
</FORM>
METHOD is way to send the data. There are two options, Post and Get. Post sends the data in single lines of text; Get squashes all the data in a single line and adds it to the URL in the Action part. If the URL was an internet address, you'd see all the data you're sending in the address bar of your browser. This sort of thing:
ProcessSurvey.html?text1=John&text2=Smith
The first name John was typed into the text box called "text1" and the surname Smith went into the text box called "text2". Form elements are separated by an ampersand ( & ). That is a direct result of using the Get method to send data. The Post method doesn't add all that code to the address bar of your browser.
You should use Post to send your data, rather than Get.
ACTION is used to specify the address where you want to send the data. Here, we're using an Email link to send the data straight to an email address:
ACTION = mailto:me@me.com
But the form can be processed by a scripting language like CGI, ASP .NET, PHP, etc. In which case you'd specify the address of the script in question:
ACTION = "ProcessSurvey.php"
To ensure that data in your forms is not sent anywhere, you can just add a pair of double quotes to the ACTION attribute:
ACTION = ""
This is good for testing purposes.

Form Elements

There are quite a few different form elements you can add to a form:
Text Boxes
Text Areas
Option Buttons
Check Boxes
Drop down List/Fixed Lists
Password Boxes
Command Buttons
Submit Buttons
Reset Buttons
Labels
Image Command Buttons
Hidden Form Values
HTML5, however, adds even more. There's even a very handy attribute called placeholder:
Placeholder
Email
Url
Number
Range
Date/Time
Search
Color
Some of these new form elements are only supported in certain browsers, however. For example, Color refers to a popup colour picker. Only the Opera web browser supports this, at the time of writing.

Text boxes, Submit and Reset Buttons


The INPUT Tag and Text Boxes

For most form elements, the word INPUT is used to set up the element. Next, you type a space followed by the word TYPE. This tells the browser what type of form elements to draw on your page. If you want a text box, the TYPE to use is "Text":
<INPUT TYPE = "Text">
(Notice that there is no end tag for INPUT.)
Next, you add the attributes you want. There are quite a lot of attributes for text boxes. The three most common ones are Size, Value, and Name. Size refers to how long the text box is in pixels rather than the number of characters it can contain. It's a good idea to limit how many text characters can fit into your text box, and for this the Maxlength attribute is used:
<INPUT TYPE = "Text" Size = 20 Value = "" Name = "text1" Maxlength="15">
The Value attribute means the text that will be typed in your text box. You can set some default text, if you like:
<INPUT TYPE = "Text" Size = 20 Value = "Default Text Here" Name = "text1">
Whatever is between the two quote marks of VALUE is what you get back when the form is sent somewhere.
Name attribute should be added so that you can refer to it in scripts. It distinguishes it from any other text box you may have on your form.
Some other text box attributes are:
Accesskey
Height
TabIndex
Width
Height and Width are self-explanatory. Accesskey refers to a keyboard shortcut you can add, while TabIndex is a number value and refers to where the cursor will end up when you press the Tab key on your keyboard. As an example, take a look at the following three text boxes:
<INPUT TYPE = "Text" TabIndex="2">
<INPUT TYPE = "Text" TabIndex="3">
<INPUT TYPE = "Text" TabIndex="1">
The third of the three text boxes above will be activated first when the tab key is pressed. Press the tab key again and the cursor will appear in the top text box, followed by the middle one. You can really annoy your visitors if you get the tab index wrong!

The Submit Button

If you want your form to be sent somewhere, a Submit button is needed (though you can write code for your own submit button). When the Submit button is clicked, the browser will check the ACTION attribute of the FORM tag to see where you want the data sent. It then checks the METHOD attribute to see what method you want to use, Post or Get. The browser will then try to send the form's data for you.
The code for a Submit button is this:
<INPUT TYPE = "Submit" Value = "Submit">
This time, the TYPE is set to "Submit". The VALUE attribute is the text that will appear on the button itself. The width of the button is determined by the width of the text for the VALUE attribute. If you wanted a really wide button, you can use this old trick:
Value = " Submit ">
Here, spaces are added to the left and right of the text. The browser will see the spaces as text and adapt the width accordingly.

The Reset Button

The Reset button returns the form to the state it was originally in when it was loaded. Any default values you added will be retained. The code for a rest button is this:
<INPUT TYPE = "Reset" Value = "Clear">
Note the TYPE is now "Reset". The value attribute works in the same way that the Submit button does - it's the text that will appear on the button.

To test out the text box element and the buttons, add the following between the BODY tags of your HTML code:
<FORM>
<INPUT TYPE="Text">
<P>
<INPUT TYPE="Submit" Value="Submit">
</FORM>
The form is just a text box and a button. Notice that the two are separated by a P tag, otherwise they'd be side-by-side.
Save your work and view the results in your browser. You should see this:
A Submit button and a text box on a HTML form
Type something into your text box and click the button. What you'll find is that the text will disappear. If you had added Method and Action attributes to the FORM tag then the text box data would be sent to a location of your choice (email address, script, etc).
Now amend your INPUT TYPE="Text" line and add SIZE and VALUE attributes:
<INPUT TYPE="Text" Size="25" Value="Enter your first name">
When you save and reload, the browser will look like this:
Default text for a text box on a HTML form
The text box will be longer and your default text will display.

Styling Form Buttons

Buttons, like any form element can have a CSS style applied. In the code below, we've applied various styles to our form button:
#Button1 {
Height: 30px;
Width: 180px;
background-color: #820404;
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
color: #FFFFFF;
}
#Button1:hover {
background-color: #CCCCCC;
}
Add an ID attribute to your button:
<INPUT TYPE="Submit" Value="Submit" ID="Button1">
Then try some CSS styles in your own code to see how they work. Try the padding and border properties to see what happens. The border-color property is also worth trying out.
Before implementing any button styles, though, it's worth checking out the results in more than one browser, especially when it comes to borders.
You can actually use images as buttons, if you like. But they need Javascript switched on in the browser to make them work. The TYPE to use is IMAGE:
<INPUT TYPE="image" SRC="image_name.gif" ALT="alt text" onClick="submit_function()">
If you're selling things on your site then image buttons may not be a good idea as some of your users won't see them.

Formatting Textboxes with CSS


You can use some CSS to format your text boxes. Add the following LINK to the HEAD section of your HTML code:
<LINK REL=Stylesheet TYPE ="text/css" HREF="../css/forms_1.css">
Create a new CSS page and save it to the correct folder. For the file name type forms_1.css. We saved our HTML page in a folder called pages. We have a CSS folder that is one folder up from this, and so saved our CSS file there. That's why our HREF reads "../css/forms_1.css". This means, "Move one folder up from where the HTML page is, and look for a folder called css. Then use the CSS script called forms_1.css."
For the CSS, type the following:
CSS to format a text box
You now need to amend your text box code slightly. Change it to this:
<INPUT ID="tb1" TYPE="Text" Value="Enter your first name">
The first line of the CSS code sets the style for an INPUT with the ID tb1. That's why we've added an ID attribute with that name to the code.
The SIZE attribute has been removed because we're setting the size of the text box using CSS:
Height: 30px;
Width: 300px;
You can leave the SIZE attribute in, though, if you like - it won't affect the results.
The other four CSS properties for the text box set the background colour, the font family and size, and the text colour.
We've also added two pseudo classes for the INPUT elements. The first one is focus. When you click inside the text box the border changes colour. Adding visual cues like this helps users when filling out your forms.
The other pseudo class is for the invalid event. You'll see how this works when we get to the HTML5 form elements. But it will put a red border around an INPUT if the user has made a mistake.
Refresh the web page in your browser. With the new CSS styles applied, it should look like this:
A text box formatted with CSS
When you click inside of the text box, it will look like this:
CSS puts a highlight around a text box
With just a few CSS styles, then, you can really improve the appearance of your form elements.

JavaScript Alert Boxes

So that you can see that something is actually happening here, we can add some simple JavaScript to get at our form values.
Add a NAME attribute to your text box code, highlighted in bold below:
<INPUT ID="tb1" TYPE="Text" Value="Enter your first name" NAME="textBox1">
Once a form element has a NAME attribute you can refer to it in code. (You can also use a form's ID attribute in code.)
The form itself needs a NAME attribute as well. So add this to your FORM tag:
<FORM NAME="frmOne">
So we've given the form the NAME frmOne.
For your form button, amend the code to this:
<INPUT TYPE="Button" Value="Submit" onClick="textBoxValue( )">
Notice that the TYPE is now "Button" instead of "Submit". This allows you to write your own submit code, which you'd want to do to check that form values have been filled in correctly.
The part that's going to do all the action, though, is this:
onClick="textBoxValue( )"
onClick is something called an event. It just means when the button is clicked perform some action. The action for us is a piece of code we're going to add in the HEAD section. We've called this piece of code textBoxValue( ).
In the HEAD section of your HTML code, add the following JavaScript:

<SCRIPT>
function textBoxValue() {
alert( document.frmOne.tb1.value );
}
</SCRIPT>
Your HTML code should now look like this:
Javascript code for an alert box
All this script does is to display a popup alert box. The text between the round brackets of alert is this:
document.frmOne.textBox1.value
It starts with the word document, which refers to the current web page displayed in your browser window. You next type the name of the form (frmOne), followed by the name of the form element (textBox1). Finally, you type the attribute you're trying to access. For us, this is the VALUE that is typed into the text box called textBox1.
Save your work, and refresh the page in your browser. Click your new button (which will look exactly like the old one). Whatever you have in the text box should appear in an alert box. Here are the results in Internet Explorer:
A javascript alert box displaying the contents of a text box
The Firefox web browser displays the following alert box:
A javascript alert box displaying the contents of a text box

Exercise
Delete your default text. Type something else into your text box, then press the Submit button. You should find the new text displays in your alert box.

Labels, Textareas


Labels

You can add labels to your form, and attach them to a specific text box or other form element. They are good when you have small elements like check boxes, as you can click on the label to select the check box.
To add a label a pair of LABEL tags are used:
<LABEL>Label Text Here</LABEL>
The text you want to go on the label goes between the two tags.
To attach a label to a particular form element the FOR attribute is used, followed by the ID of the form element you want to attach it to. For example, examine the code below:
<LABEL FOR="tb1">First Name: </LABEL>
<INPUT ID="tb1" TYPE="Text" Value="Enter your first name" NAME="textBox1">
In the code above, the LABEL is FOR a form element with the ID "tb1". Here's what it looks like in the
A HTML form showing a label and text box
In the image above, we have clicked on the label. This highlights the text in the text box. A user can then just type a first name, without having to click inside of the text box. The label does this because it knows which text box it is "FOR".

TEXTAREA

If you want a bigger text box, for people to leave comments for example, then you can use the TEXTAREA tag.
Textarea doesn't use the INPUT tag. And you need an end Textarea tag, as well. After typing a space, you specify how big your Textarea is going to be. You do this with the ROWS and COLS attributes. The Height equates to Rows, and the Width to Cols (not Columns):
<TEXTAREA ROWS="7" COLS="30" NAME="TextArea1" ID="TA1">
</TEXTAREA>
If you want some default text to appear in the Textarea then you can type it between the two tags:
<TEXTAREA ROWS="7" COLS="30" NAME="TextArea1" ID="TA1">
Default text area
</TEXTAREA>
The text area above would then look like this in Firefox version 4 and later:
A HTML form showing a textarea
Notice the little triangle in the bottom right. Hold your mouse down over the triangle and you can drag to resize it. (Only Firefox has this, at the time of writing.)
You can also attach a label to the Textarea. You do it in exactly the same way as for text boxes:
<LABEL FOR="TA1">Comments:</LABEL>
<TEXTAREA ROWS="7" COLS="30" NAME="TextArea1" ID="TA1">
Default text area
</TEXTAREA>

Exercise
Add a Textarea to your own form. Apply some CSS styling to liven it up a little.

Option Buttons, Check Boxes, List Boxes


Option Buttons

Option buttons are sometimes called Radio Buttons, and they force the user into choosing only one item in a list, such as a Male/Female option, or selecting a payment method.
The Option button HTML look like this:
<INPUT TYPE="Radio" Name="Gender" Value="Male">Male
<INPUT TYPE="Radio" Name="Gender" Value="Female">Female
After typing the INPUT tag, the word TYPE comes next. For Option Buttons, the type is "Radio". The NAME is definitely needed here, and note that the NAME for both in our code above is "Gender". You use the same name for each group of option buttons you are adding to your form. So if you wanted payment option buttons, the code might be this:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
This time, each radio button has the name "payment". The reason you keep the same name for each group of option buttons is simply to distinguish one group of option buttons from another.
The VALUE attribute is quite useful. When the user submits the form to you using the Submit button, these VALUES are going to be returned. If you've just got Radio1 and Radio2, you won't know (or won't remember, more likely) which option the user has selected. Manipulating values with scripts is also a lot easier if the Value is the same as the text the user sees.
If you want to have a default option button selected, use the word "Checked":
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP" Checked>PayPal
Attaching a label to each button is very useful for your visitors. When the label is clicked it will select the option button it is named for:
<LABEL FOR="R1">Male</LABEL>
<INPUT TYPE="Radio" Name="Gender" ID="R1" Value="Male">
<LABEL FOR="R2">Female</LABEL>
<INPUT TYPE="Radio" Name="Gender" ID="R2" Value="Female">
In the code above, the labels are FOR the form elements called R1 and R2. We have added a corresponding ID to each option button. Notice, too, that we've deleted the text from after the > of each option button. The "Male" and "Female" text is now between the two label tags.

Check Boxes

Check boxes are used to give your users the opportunity to select more than one option from a range of options. With the Radio Buttons, you could only select one item; with check boxes, you can select them all.
The HTML for check boxes looks like this:
<INPUT TYPE="Checkbox" Name="Browser" Value ="Firefox">Firefox
<INPUT TYPE="Checkbox" Name= "Browser" Value ="Opera ">Opera
Again, you can add a label to aid in selection:
<LABEL FOR="C1">Firefox</LABEL>
<INPUT TYPE="Checkbox" Name="Browser" ID="C1" Value="Firefox">
<LABEL FOR="C2"> Opera </LABEL>
<INPUT TYPE="Checkbox" Name="Browser" ID="C2" Value="Opera">
Check boxes and Radio buttons work in a similar way, and the HTML code is similar, too. The same points made about Radio buttons apply to check boxes. Note the TYPE used, though: Checkbox.
The above code for option buttons and checkboxes would look like this in the browser:
A HTML form showing radio buttons and check boxes

List Boxes

You can have a list box of items on your forms, either in a drop down format or as a fixed list. Here's what the two look like on a web page:
A HTML form showing two list boxes
The HTML code for a dropdown list, the default, is this:
<SELECT>
<OPTION Value="Under 16">Under 16</OPTION>
<OPTION Value="16 to 25">16 to 25</OPTION>
<OPTION Value="26 to 40">26 to 40</OPTION>
<OPTION Value="40 to 60">40 to 60</OPTION>
<OPTION Value="Over 60">Over 60</OPTION>
</SELECT>
List boxes are called Select boxes in HTML and use the <SELECT> tag to set them up.
Each item in your list needs an OPTION tag.
<OPTION Value="Under 16">Under 16</OPTION>
You don't need the closing OPTION tag, if you don't want it, but it is here for the sake of neatness. The text you want to appear in the list, the text that people see and click on, goes after the first right pointy bracket (>). The Value is not strictly needed, either. When the form is submitted, the option the user selected will be returned to you. If the Value attribute is missing, the text itself will be returned.
If you want one of the items in your list selected by default, just choose the item and add SELECTED as an attribute. Like this:
<OPTION Value="Under 16" SELECTED>Under 16
The only difference between the drop down list and the Fixed list is one attribute in the <SELECT> tag: SIZE.
<SELECT SIZE="5">
The SIZE is the number of item in your list. If you add this attribute, you'll get a Fixed list instead of a drop down list.
If you want your users to be able to choose more than one item from the list, the attribute to add to the SELECT tag is MULTIPLE
<SELECT SIZE="5" MULTIPLE>
A user can then hold down the CTRL key and click to select more than one item.
You can add CSS styles to your list boxes, of course. Here's a style that sets font properties using the HTML selector:
SELECT {
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
}
Now everything with the HTML SELECT tag will have its font and font size changed.

Password Boxes, The Hidden Element


Password Boxes

You can add a password box to your form. This is identical to a text box in its appearance. The only difference is that when you type in the box the characters are replaced by asterisks ( * ). It's important to remember that although a password box hides the text from prying eyes, the data is not encrypted in any way. If you use METHOD=Get instead of Post, the password would show up in the address line of the browser.
The code for a password box is this:
<INPUT TYPE="Password" SIZE="20" MAXLENGTH="8">
The MAXLEGTH attribute is the maximum number of characters that can be entered into the password text box. SIZE is how wide you want the password box to be.

Hidden Elements

You can have something called a Hidden Element on your form. Hidden elements are for your benefit, not your users. You can store information in a hidden element, and then pass the information to a second web page or form.
The Code for a hidden element is this:
<INPUT TYPE="Hidden" NAME="H1" VALUE="Some value">
As the name of the element implies, any data stored in the VALUE attribute does not show up on the page. However, if a viewer clicks View > Source in a browser, your code can be seen, and that includes any values you've hard-coded into the Value attribute of the Hidden element. So you wouldn't use the Hidden element to store sensitive data.

HTML Form Tags

   Main Form Tags   Comments
FormCreate a HTML form
NameAdd a name for your form
MethodSelect a method, GET or POST
ActionSay where the form should be sent
InputCreate a HTML form element
TypeSelect a type of form element
LabelAdd a label for a form element
ValueA value for your form elements

HTML Form Elements

   Input Types   Comments
ButtonCreate a clickable button
CheckboxCreate a checkbox
HiddenCreate a hidden form element
ImageSpecify an image to be used as a button
PasswordSet up a password box
RadioCreate a radio/option button
ResetCreate a reset button
SubmitCreate a submit button for your forms
TextCreate a text box

HTML5 Form Elements and Attributes

HTML5 Form ElementsComments and Options
PlaceholderPlaceholder text
RequiredRequire an element to be filled in
EmailEmail text box
URLURL text box
NumberNumber spinners
RangeSliders with a range of numbers
Date/TimeDate and time textbox or calendar
SearchA search box
ColorColour picker
DatalistUsed with datalists are LIST, OPTION, VALUE, LABEL

Comments

  1. Thanks for such an amazing information. I have just read it. It really helps.
    If you are looking for other articles just visit20 Simple Ways to Increase Productivity

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for such an amazing information. I have read it. Usefull for me. Check my site at Artamajon

    ReplyDelete
  4. Now, i can to make make form to my blog, thank for sharing this tutorial.
    lets check form on my blog here Cara Mendapatkan Uang

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Thanks for such an amazing information. I have just read it. It really helps.
    If you are looking for other articles just visit here

    ReplyDelete

Post a Comment