Forms: select box - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

55
Forms: select box

The standard way to ask the user to tell you the state he lives in is the select box. A select box works well when you want the user to select from a list that’s too long to be handled gracefully by radio buttons. Like radio buttons, only one selection can be made in a select box. Let’s add one for a state selection. I’ll just do three states to show you how it works.

This is the code.

<form action="send-email.php" method="post">
Last name:
<br>
<input type="text" name="surname" size="25"maxlength="40">
<br><br>
How did you find us?<br>
<input type="radio" name="found-thru" value="Google" checked="checked"> Google
<input type="radio" name="found-thru" value="Review"> Review
<input type="radio" name="found-thru" value="Friend"> Friend
<br><br>
How would you describe our site?<br>
<input type="checkbox" name="feedback" value="Wonderful" checked="checked"> Wonderful
<input type="checkbox" name="feedback" value="Fabulous"> Fabulous
<input type="checkbox" name="feedback" value="Brilliant"> Brilliant
<br><br>
Your state:<br>
<select name="current-state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<br><br>
Message:
<br>
<textarea name="message" rows="4" cols="30"></textarea>
<br><br>
<input type="submit" value="Send email message">
</form>

The syntax for a select box is different than the syntax you’ve learned for other input types.

· Starts with <select, not <input type=

· Unlike radio buttons and checkboxes, which are freestanding and bound together by a common name, all the choices are enclosed by opening and closing select tags.

· Unlike most other input types, option tags are closed.

· The name is specified only once, in the select tag.

By default, the first option is pre-selected. In the example, it’s Alabama. You can pre-select another option by including in one of the option tags the words select="selected".

A problem with the example is that if the user doesn’t bother to make a selection, his state will be input as Alabama even if he lives in Alaska, since Alabama defaults as the choice if the user doesn’t make one. The solution is to make the first option something like “Select a state.” When the user clicks the input button, a little JavaScript routine can check to see whether “Select a state” is the selected option, which means that the user hasn’t made a selection. If so, the user can be prompted to select a state. My book A Smarter Way to Learn JavaScript, available at Amazon, shows you how to write this routine.

In your HTML file add a select box with two selections to the form you’ve already coded. Save the file. Display the page.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-55-1.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/55.html