Java Reference
In-Depth Information
If there is no Wednesday option, you then need to make space for the new Wednesday option to be
inserted.
Before you do this, you defi ne two variables: indexCounter and days (which refers to theDay select
element and is a shorthand reference for your convenience). At this point, there are six options (the last
element is as index 5), so next you create a new option with the variable name lastoption and assign
it to the element at the end of the collection. This new element is assigned at index position 6 by using
the length property of the options collection, which previously had no contents. You next assign the
text and value properties of each of the Option objects from Thursday to Sunday to the Option at an
index value higher by one in the options array, leaving a space in the options array at position 2 to
put Wednesday in. This is the task for the for loop within the if statement.
Next, you create a new Option object by passing the text “Wednesday” and the value 2 to the Option
constructor. The Option object is then inserted into the options collection at position 2, and presto, it
appears in your select box.
var option = new Option(“Wednesday”, 2);
days.options[2] = option;
}
You end the function by alerting the user to the fact that there is already a Wednesday option in the list,
if the condition in the if statement is false.
else
{
alert(“Do you want to have TWO Wednesdays?????”);
}
}
This example works in every browser; however, all modern browsers provide additional methods to
make adding and removing options easier.
Adding New Options with Standard Methods
In particular, the Select object you are interested in has additional add() and remove() methods,
which add and remove options. These make life a little simpler.
Before you add an option, you need to create it. You do this just as before, using the new operator.
The Select object's add() method enables you to insert an Option object that you have created
and accepts two parameters. The fi rst parameter is the Option object you want to add. The second
parameter, unfortunately, varies depending on the browser. In Firefox, Safari, Chrome, Opera, and IE8
Standards mode, the second parameter is the Option object you want to place the new Option object
before. In IE7 (or IE8 non-standards mode), the second parameter is the index position you want to add
the option in. In all browsers, you can pass null as the second parameter, and the added Option object
will be added at the end of the options collection.
The add() method won't overwrite any Option object already at that position, but instead will simply
move the Option objects up in the collection to make space. This is basically the same as what you had
to code into the btnAddWed_onclick() function using your for loop.
Search WWH ::




Custom Search