Checkboxes and radio buttons are used in two different ways. You use radio buttons for a list of multiple options that are mutually exclusive and from which users can select only one. Checkboxes are for multiple options from which users can choose any number. Despite this distinction, the primary purpose of both is to give users a number of options to choose from.
They also have something else in common: Their DOM objects share the same properties, methods, and events. But scripting them can be a little different due to how they are represented in the DOM. This lesson teaches you how to write JavaScript against these controls, starting with the checkbox.
You generate checkboxes by using the <input/>
element and setting its type
attribute to checkbox
, as shown in the following HTML:
<input type="checkbox" name="color" value="Red" checked="checked" />
This HTML creates a checkbox named color
with a value of Red
that is checked by default because of the presence of the checked
attribute. In the DOM, just as with all other form controls, the name
and value
attributes are available to you as properties of the checkbox's DOM object. The checked
attribute maps to a property of the same name, but the property's value is either true
or false
(as opposed to the checked
attribute's value in the previous HTML code). So you can change the checked state of a checkbox by assigning a Boolean value to the checked
property, like this:
var chkBox = theForm.color; chkBox.checked = false;
This code gets a reference of the checkbox DOM object (assuming it's in a form called theForm
) and uses the checked
property to uncheck the box. Scripting a checkbox individually, as in this example, is a common approach to checkbox scripting. Sometimes you need to do something specific when a particular checkbox is checked, and the action performed as a result of the click
event depends on the checkbox's checked state. For example, you may want to enable or disable parts of a form based on whether or not a particular checkbox is checked. You'll do something similar in code later in this lesson.
You can also group two or more checkboxes together by using the same name for each checkbox, like this:
<input type="checkbox" name="color" value="Red" checked="checked" /> <input type="checkbox" name="color" value="Blue" checked="checked" /> <input type="checkbox" name="color" value="Green" checked="checked" />
This HTML adds two more checkboxes, and all three <input/>
elements have the same name: color
. So this is a checkbox group named color
. In the DOM, grouping checkboxes creates a NodeList
of checkboxes, and you access this NodeList
by using the name of the checkbox group, like this:
var colorBoxes = theForm.color; alert(colorBoxes.length); // 3
This code gets a reference to the color
checkbox group and assigns it to the colorBoxes
variable. Remember from way back in Lesson 13 that a NodeList
is an array-like object, and as such has a length
property. So the alert box shows a value of 3
. The length
property makes it possible to loop through the NodeList
and determine which checkboxes in the group are checked. Look at the following code:
var colors = []; for (var i = 0; i < colorBoxes.length; i++) { var chkBox = colorBoxes[i]; if (chkBox.checked) { colors.push(chkBox.value); } } alert("You picked: " + colors.join(", "));
This code loops through the checkboxes in the color
group, determines which checkboxes are checked, adds the value of the checked checkboxes to the colors
array, and then displays the picked colors to the user.
Radio buttons are almost always placed in radio button groups. You can script them as you would script checkbox groups.
Radio buttons are also generated with the <input/>
element, but their type
attribute is set to radio
, like this:
<input type="radio" name="color" value="Red" /> <input type="radio" name="color" value="Blue" /> <input type="radio" name="color" value="Green" />
This HTML creates the radio button version of the color
checkbox group from the previous section. In it are three radio buttons, and users can choose only one of these items, since they are grouped together.
Even though it is omitted in this HTML example, radio button controls have a checked
attribute and property, and you can write code like the checkbox group code from the previous section to determine if a radio button in a particular group has been checked, like this:
var colorButtons = theForm.color; for (var i = 0; i < colorButtons.length; i++) { var rdoButton = colorButtons[i]; if (rdoButton.checked) { // do something with verified data } }
You use something similar to this code next in the Try It section.
In this lesson, you learn how to script single and multiple checkboxes, as well as radio button groups. You learn that in addition to the standard form control properties, both checkboxes and radio controls have a checked
property to determine whether or not the control is checked.
For this lesson, you need a text editor; any plain text editor will do. For Microsoft Windows users, Notepad is available by default on your system or you can download Microsoft's free Visual Web Developer Express (www.microsoft.com/express/web/
) or Web Matrix (www.asp.net/webmatrix/
). Mac OS X users can use TextMate, which comes as part of OS X, or download a trial for Coda (www.panic.com/coda/
). Linux users can use the built-in VIM.
You also need a modern web browser. Choose any of the following:
Internet Explorer 8+
Google Chrome
Firefox 3.5+
Apple Safari 4+
Opera 10+
Create a subfolder called Lesson30
in the JS24Hour
folder you created in Lesson 1. Store the files you create in this lesson in the Lesson30
folder.
Type the following HTML and JavaScript:
<html> <head> <title>Lesson 30: Example 01</title> </head> <body> <form name="theForm" action="" onsubmit="validateForm(event)"> <p> Name: <input type="text" name="txtName" /> </p> <p> Age: <input type="text" name="txtAge" /> </p> <p> Email: <input type="text" name="txtEmail" /> </p> <p> Password: <input type="password" name="txtPassword1" /> </p> <p> Retype Password: <input type="password" name="txtPassword2" /> </p> <p> Your Favorite Day: <select id="dayOfTheWeek" name="dayOfTheWeek"> </select> </p><p>
Please choose your favorite color:
</p>
<p>
<input type="radio" name="color" value="Red" /> Red
</p>
<p>
<input type="radio" name="color" value="Blue" /> Blue
</p>
<p>
<input type="radio" name="color" value="Green" /> Green
</p>
<p>
</p>
<p>
<input type="checkbox" name="userAgree"
onclick=" userAgreeClick(event)" />
I agree to use this form.
</p>
<input name="btnSubmit" type="submit" value="Submit"disabled="disabled"
</form> <script type="text/javascript" src="eventutility.js"></script> <script type="text/javascript"> function populateDays() { var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; var dayOfWeek = document.getElementById("dayOfTheWeek"); var today = (new Date()).getDay(); for (var i = 0; i < days.length; i++) { var length = dayofWeek.options.length; dayOfWeek.add(new Option(days[i], i), length); } dayOfWeek.selectedIndex = today; } function isEmpty(value) { return (value === ""); } function validateForm(event) { var theForm = document.theForm, txtName = theForm.txtName, txtAge = theForm.txtAge, txtEmail = theForm.txtEmail, txtPassword1 = theForm.txtPassword1, txtPassword2 = theForm.txtPassword2, button = theForm.btnSubmit, age = parseInt(txtAge.value); button.disabled = true; // validate name field if (!isEmpty(txtName.value)) { // validate age if (!isNaN(age) && age > 0) { // validate email field if (txtEmail.value.indexOf("@") > 0) { // validate password - pass 1 if (!isEmpty(txtPassword1.value)) { // validate password - pass 2 if (txtPassword1.value === txtPassword2.value) { return; } else {
alert("Passwords do not match. Please reenter them."); txtPassword1.focus(); txtPassword1.select(); } } else { alert("Password cannot be blank."); txtPassword1.focus(); txtPassword1.select(); } } else { alert("Please enter a valid email address."); txtEmail.focus(); txtEmail.select(); } } else { alert("Please enter your age."); txtAge.focus(); txtAge.select(); } } else { alert("Please enter your name."); txtName.focus(); } button.disabled = false; eventUtility.preventDefault(event); } populateDays(); </script> </body> </html>
Save this as lesson30_example01.htm
. This is a modified version of the form you ended up with at the end of Lesson 29. The bold code shows you what was added to the file. A radio button group, called color
, was added to the page, and a checkbox named userAgree
was added as well. It has an onclick
event handler that calls the function userAgreeClick()
, which you write in the next step. Also, a disabled
attribute was added to the submit button, disabling it by default.
The checkbox's purpose is similar to that of checkboxes on other forms you may have seen on the Internet, where you must agree to a set of terms before submitting. When the user clicks the checkbox, the submit button should be enabled. Write the userAgreeClick()
function to enable the button. It is bold in the following code:
<html> <head> <title>Lesson 30: Example 01</title> </head> <body> <form name="theForm" action="" onsubmit="validateForm(event)">
<!-- Removed for Printing --> <p> Please choose your favorite color: </p> <p> <input type="radio" name="color" value="Red" /> Red </p> <p> <input type="radio" name="color" value="Blue" /> Blue </p> <p> <input type="radio" name="color" value="Green" /> Green </p> <!-- Removed for Printing --> </form> <script type="text/javascript" src="eventutility.js"></script> <script type="text/javascript"> function populateDays() { // removed for printing }function userAgreeClick(event) {
var eSrc = eventUtility.getTarget(event);
var button = theForm.btnSubmit;
button.disabled = !eSrc.checked;
}
function isEmpty(value) { return (value === ""); } function validateForm(event) { // removed for printing } populateDays(); </script> </body> </html>
The first statement of this function gets the event target (the checkbox) and the form's submit button. Then the button's disabled
property is set to the opposite of whatever the checkbox's checked
property is. When checked
is true
the button's disabled
property should be false
, and vice versa.
The color
radio button group does not have a default option checked so you need to write a function to ensure that users pick one of the three options. Name the function validateColor()
. It is bold in this code:
<html> <head> <title>Lesson 30: Example 01</title> </head> <body>
<form name="theForm" action="" onsubmit="validateForm(event)"> <!-- Removed for Printing --> <p> Please choose your favorite color: </p> <p> <input type="radio" name="color" value="Red" /> Red </p> <p> <input type="radio" name="color" value="Blue" /> Blue </p> <p> <input type="radio" name="color" value="Green" /> Green </p> <!-- Removed for Printing --> </form> <script type="text/javascript" src="eventutility.js"></script> <script type="text/javascript"> function populateDays() { // removed for printing } function userAgreeClick(event) { // removed for printing }function validateColor() {
var colorButtons = document.theForm.color;
for (var i = 0; i < colorButtons.length; i++) {
if (colorButtons[i].checked) {
return true;
}
}
return false;
}
function isEmpty(value) { return (value === ""); } function validateForm(event) { // removed for printing } populateDays(); </script> </body> </html>
The job of this function is simply to return true
if one of the radio buttons is checked, and false
otherwise. A for
loop loops through the radio button group and checks each radio button's checked
property. If one is checked, the function returns true
. If the loop iterates over each color
radio button without finding a checked one, the function returns false
.
Now modify the validateForm()
function to use the validateColor()
function. Changes are in bold in the following code:
function userAgreeClick(event) { // removed for printing }function validateColor() {
var colorButtons = document.theForm.color;
for (var i = 0; i < colorButtons.length; i++) {
if (colorButtons[i].checked) {
return true;
}
}
return false;
}
function isEmpty(value) { return (value === ""); } function validateForm(event) { var theForm = document.theForm, var txtName = theForm.txtName; var txtAge = theForm.txtAge; var txtEmail = theForm.txtEmail; var txtPassword1 = theForm.txtPassword1; var txtPassword2 = theForm.txtPassword2; var button = theForm.btnSubmit; var age = parseInt(txtAge.value); button.disabled = true; // validate name field if (!isEmpty(txtName.value)) { // validate age if (!isNaN(age) && age > 0) { // validate email field if (txtEmail.value.indexOf("@") > 0) { // validate password - pass 1 if (!isEmpty(txtPassword1.value)) { // validate password - pass 2 if (txtPassword1.value === txtPassword2.value) {// validate color
if (validateColor()) {
return;
} else {
alert("Please choose your favorite color");
}
} else {
alert("Passwords do not match. Please reenter them.");
txtPassword1.focus();
txtPassword1.select();
}
} else {
alert("Password cannot be blank.");
txtPassword1.focus();
txtPassword1.select();
}
} else {
alert("Please enter a valid email address.");
txtEmail.focus();
txtEmail.select();
}
} else {
alert("Please enter your age.");
txtAge.focus();
txtAge.select();
}
} else {
alert("Please enter your name.");
txtName.focus();
}
button.disabled = false;
eventUtility.preventDefault(event);
}
populateDays();
</script>
</body>
</html>
Since validateColor()
returns a Boolean value, it's used as the condition in the new if
statement. If it validates, validateForm()
returns and the form submits. If not, an alert box displays a message to the user asking him or her to pick a color.
Make sure you save the file, and run it in any browser to test the new functionality.
To get the sample code files, you can download Lesson 30 from the book's website at www.wrox.com
.
Please select Lesson 30 on the DVD to view the video that accompanies this lesson.
3.128.205.21