Java Reference
In-Depth Information
Within the body of the page, you defi ne a form with the name form1. This contains the select element,
which includes day-of-the-week options that you have seen previously. The form also contains two but-
tons, as shown here:
<input type=”button” value=”Remove Wednesday” name=”btnRemoveWed”
onclick=”btnRemoveWed_onclick()“ />
<input type=”button” value=”Add Wednesday” name=”btnAddWed”
onclick=”btnAddWed_onclick()“ />
Each of these buttons has its onclick event handler connected to some code that calls one of two func-
tions: btnRemoveWed_onclick() and btnAddWedc`_onclick() . These functions are defi ned in a
script block in the head of the page. You'll take a look at each of them in turn.
At the top of the page you have the fi rst function, btnRemoveWed_onclick() , which removes the
Wednesday option.
function btnRemoveWed_onclick()
{
if (document.form1.theDay.options[2].text == “Wednesday”)
{
document.form1.theDay.options[2] = null;
}
else
{
alert('There is no Wednesday here!');
}
}
The fi rst thing you do in the function is a sanity check: You must try to remove the Wednesday option
only if it's there in the fi rst place! You make sure of this by seeing if the third option in the collection
(with index 2 because arrays start at index 0) has the text “Wednesday”. If it does, you can remove
the Wednesday option by setting that particular option to null. If the third option in the array is not
Wednesday, you alert the user to the fact that there is no Wednesday to remove. Although this code
uses the text property in the if statement's condition, you could just as easily have used the value
property; it makes no difference.
Next you come to the btnAddWed_onclick() function, which, as the name suggests, adds the Wednesday
option. This is slightly more complex than the code required to remove an option. First, you use an if
statement to check that there is not already a Wednesday option.
function btnAddWed_onclick()
{
if (document.form1.theDay.options[2].text != “Wednesday”)
{
var indexCounter;
var days = document.form1.theDay;
var lastoption = new Option();
days.options[days.options.length] = lastoption;
for (indexCounter = days.options.length - 1;
indexCounter > 2; indexCounter--)
{
days.options[indexCounter].text =
days.options[indexCounter - 1].text;
days.options[indexCounter].value =
days.options[indexCounter - 1].value;
}
Search WWH ::




Custom Search