Java Reference
In-Depth Information
first need to register the click event listeners on their respective elements. As in previous examples, first
create a variable called myForm to reference the form in the document:
var myForm = document.form1;
Now, register the click event listener on your radio buttons. Unfortunately, there's no magical command
that says “use this function to handle all the radio buttons' click events.” So, you'll have to call
addEventListener() on every Radio object. This isn't as difficult as it sounds; a for loop will help you:
for (var index = 0; index < myForm.radCpuSpeed.length; index++) {
myForm.radCpuSpeed[index].addEventListener("click", radCpuSpeedClick);
}
This for loop is fairly straightforward except for one thing: myForm.radCpuSpeed . What you are doing
here is using the collection for the radCpuSpeed radio group. Each element in the collection actually
contains an object, namely each of your three Radio objects. Therefore, you're looping over the Radio
objects in the radCpuSpeed radio group, retrieving the Radio object at the given index, and calling its
addEventListener() method.
Next, register the event listener for the form's standard button:
myForm.btnCheck.addEventListener("click", btnCheckClick);
Now let's look at the radCpuSpeedClick() function, the function that executes when the radio buttons
are clicked. The first thing this function needs to do is to find the index of the event target in the
radCpuSpeed radio group:
function radCpuSpeedClick(e) {
var radIndex = findIndexOfSpeed(e.target);
You do this by calling the findIndexOfSpeed() helper function. We'll look at this function later, but for
now, just know that it finds the index of the supplied Radio object in the myForm.radCpuSpeed collection.
The default action of clicking a radio button is to check the radio button. If you prevent the default
action from occurring, the radio button will not be checked. As an example of this in action, you have
an if statement on the next line. If the radio button's index value is 1 (that is, if the user checked the
box for a 3.7 GHz processor), you tell the user that it's out of stock and cancel the clicking action by
calling the Event object's preventDefault() method:
if (radIndex == 1) {
e.preventDefault();
alert("Sorry that processor speed is currently unavailable");
As previously mentioned, canceling the clicking action results in the radio button not being checked. In
such a situation, all browsers (except for IE) recheck the previously checked radio button. IE, however,
removes all checks from the radio group. To rectify this, you reset the radio group:
// to fix an issue with IE
myForm.radCpuSpeed[0].checked = true;
}
}
Search WWH ::




Custom Search