BEGINNING JAVASCRIPT PART 5 – THE SELECT ELEMENTS (Page 1)

The SIZE attribute of the <SELECT> tag is used to specify how many of the options are visible to the user.

For example, to create a list box that is 5 rows deep and populate it with 7 options, our <SELECT> tag would look like this:

<SELECT NAME=theDay SIZE=5>
<OPTION VALUE=0 SELECTED>Monday
<OPTION VALUE=1>Tuesday
<OPTION VALUE=2>Wednesday
<OPTION VALUE=3>Thursday
<OPTION VALUE=4>Friday
<OPTION VALUE=5>Saturday
<OPTION VALUE=6>Sunday
</SELECT>

Notice that the Monday <OPTION> tag also contains the word SELECTED; this will make this option the default selected one when the page is loaded. The values of the options have been defined as numbers, but text would be equally valid.

If we wanted this to be a drop-down list, then we just need to change the SIZE attribute in the <SELECT> tag to 1 and hey presto it’s a drop-down list.

If we want to let the user choose more than one item from a list at once, we simply need add the MULTIPLE attribute to the <SELECT> definition.

The <SELECT> tag creates a Select object. This object has an options[] array property, and this array is made up of Option objects, one for each <OPTION> element inside the <SELECT> element associated with the Select object. For example, in the above example if the <SELECT> element was contained in a form called theForm, with

document.theForm.theDay.options[0]

we would access the option created for Monday.

How can we tell which option has been selected by the user? Easy; we use the Select object’s selectedIndex property. We can use the index value returned by this property to access the selected option using the options[] array.

The Option object also has index, text, and value properties. The index property returns the index position of that option in the options[] array. The text property is what’s displayed in the list and the value property is the value defined for the option, which would be posted to the server if the form were submitted.

If you want to find out how many options there are in a select element, you can use the length property of either the Select object itself or of its options[] array property.

Let’s see how we could loop through the options[] array for the above select box:

var theDayElement = window.document.form1.theDay; 
document.write("There are " + theDayElement.length + "options"); 
var optionCounter;
for (optionCounter = 0; optionCounter < theDayElement.length;
    optionCounter++) 
{
  document.write("Option text is " + 
          theDayElement.options[optionCounter].text) 
  document.write(" and its value is ");
  document.write(theDayElement.options[optionCounter].value);
  document.write("") 
}

First we set the variable theDayElement to reference the Select object. Then we write the number of options to the page, in this case 7.

Next we use a for loop to loop through the options[] array, displaying the text of each option, such as Monday, Tuesday etc., and its value, such as 0, 1 etc. If you create a page based on this code, it must be placed after the <SELECT> tag has been defined.

It’s also possible to add options to a select element after the page has finished loading. We’ll look at how this is done next.

Adding New Options

To add a new option to a select element, we simply create a new Option object using the new operator, and then insert it into the options[] array of the Select object at an empty index position.

When creating a new Option object there are two parameters to pass, the first is the text you want to appear in the list, the second the value to be assigned to the option.

var myNewOption = new Option("TheText","TheValue");

We then simply assign this Option object to an empty array element, for example:

document.theForm.theSelectObject.options[0] = myNewOption;

If you want to remove an option you simply set that part of the options[] array to null. For example, to remove the element we just inserted above, we need:

document.theForm.theSelectObject.options[0] = null;

When you remove an Option object from the options[] array, the array is reordered so that the array index values of all the options above the removed one have their index value decremented by one.

When you insert a new option at a certain index position, beware that it will overwrite any Option object that is already there.

Try It Out – Adding and Removing List Options

Let’s use the ‘list of days’ example we saw above to demonstrate adding and removing list options.

<HTML>
<HEAD>

<SCRIPT LANGUAGE=JavaScript>

function butRemoveWed_onclick() 
{
  if (document.form1.theDay.options[2].text == "Wednesday") 
  {
   document.form1.theDay.options[2] = null;
  } 
  else 
  {
   alert('There is no Wednesday here!');
  }
}

function butAddWed_onclick() 
{
  if (document.form1.theDay.options[2].text != "Wednesday") 
  {
   var indexCounter;
   var days = document.form1.theDay;
   var lastoption = new Option();
   days.options[6] = lastoption;

   for (indexCounter = 6;indexCounter > 2; indexCounter--)
   {
   days.options[indexCounter].text = 
          days.options[indexCounter - 1].text;
   days.options[indexCounter].value = 
          days.options[indexCounter - 1].value;
   }

   var option = new Option("Wednesday",2);
   days.options[2] = option;
  }
  else 
  {
   alert('Do you want to have TWO Wednesdays?????');
  }
}

</SCRIPT>
</HEAD>
<BODY>

<FORM NAME=form1>
<SELECT NAME=theDay SIZE=5>
  <OPTION VALUE=0 SELECTED>Monday
  <OPTION VALUE=1>Tuesday
  <OPTION VALUE=2>Wednesday
  <OPTION VALUE=3>Thursday
  <OPTION VALUE=4>Friday
  <OPTION VALUE=5>Saturday
  <OPTION VALUE=6>Sunday
</SELECT>
<BR>
<INPUT TYPE="button" VALUE="Remove Wednesday" NAME=butRemoveWed 
  onclick="butRemoveWed_onclick()">
<INPUT TYPE="button" VALUE="Add Wednesday" NAME=butAddWed 
  onclick="butAddWed_onclick()">
<BR>
</FORM>
</BODY>
</HTML>

Save this as ch6_examp7.htm.

If you type the page in and load it into your browser, you should see the form below. Click the Remove Wednesday button and you’ll see it disappear from the list. Add it back by clicking the Add Wednesday button. If you try and add a second Wednesday or remove a non-existent Wednesday, then you’ll get a polite warning telling you that you can’t do that.

image1 BEGINNING JAVASCRIPT PART 5 - THE SELECT ELEMENTS
       (Page 1)

How It Works

Within the body of the page, we define a form with the name form1. This contains the select element containing day of the week options that we have seen above. The form also contains two buttons:

<INPUT TYPE="button" VALUE="Remove Wednesday" NAME=butRemoveWed 
  onclick="butRemoveWed_onclick()">
<INPUT TYPE="button" VALUE="Add Wednesday" NAME=butAddWed 
  onclick="butAddWed_onclick()">

Each of these buttons has its onclick event handler connected to some code that calls one of two functions: butRemoveWed_onclick() and butAddWed_onclick(). These functions are defined in a script block in the head of the page. We’ll take a look at each of them in turn.

At the top of the page we have our first function, butRemoveWed_onclick(), which removes the Wednesday option.

function butRemoveWed_onclick() 
{
  if (document.form1.theDay.options[2].text == "Wednesday") 
  {
   document.form1.theDay.options[2] = null;
  } 
  else 
  {
   alert('There is no Wednesday here!');
  }
}

The first thing we do in the function is a sanity check: we must only try to remove the Wednesday option if it’s there in the first place! We do this by seeing if the third option in the array, with index 2 because arrays start at index 0, has the text “Wednesday”. If it does we can remove the Wednesday option by setting that particular option to null. If the third option in the array is not Wednesday, then we alert the user to the fact that there is no Wednesday to remove. Although I’ve used the text property in the if statement’s condition, we could just have easily used the value property; it makes no difference.

Next we come to the butAddWed_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 we use an if statement to check that there is not already a Wednesday option.

function butAddWed_onclick() 
{
  if (document.form1.theDay.options[2].text != "Wednesday") 
  {
   var indexCounter;
   var days = document.form1.theDay;
   var lastoption = new Option();
   days.options[6] = lastoption;

   for (indexCounter = 6;indexCounter > 2; indexCounter--)
   {
   days.options[indexCounter].text = 
          days.options[indexCounter - 1].text;
   days.options[indexCounter].value = 
          days.options[indexCounter - 1].value;
   }

If there is no Wednesday option, we then need to make space for the new Wednesday option to be inserted.

Before we do this we define two variables indexCounter and days, which refers to theDay select element and is a shorthand reference for our convenience. Next we create a new option with the variable name lastoption and assign this new option to the element at index position 6 in our options array. This previously had no contents. We next assign the text and value properties of all the Option objects from Thursday to Sunday to the Option that is at a one higher index 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, we 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[] array at position 2, and hey presto it appears in our select box.

   var option = new Option("Wednesday",2);
   days.options[2] = option;
  }

We 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?????');
  }
}

Adding New Options with Internet Explorer

In IE there are many more additional properties, methods, and events associated with objects. In particular, the options[] array we are interested in has the additional add() and remove() methods, which add and remove options. These make life a little simpler.

Before we add an option, we need to create it. This is done in exactly the same way as before, using the new operator.

The add() method allows us to insert an Option object that we have created, and takes two parameters. We pass the option that we want to add as the first parameter. The optional second parameter allows us to specify which index position we want to add the option in. This won’t overwrite any Option object already at that position, but simply moves the Option objects up the array to make space. This is basically the same as what we had to code into the butAddWed_onclick() function using our for loop.

Using the add() method, we can rewrite the butAddWed_onclick() function in our ch6_examp7.htm example to look like this:

function butAddWed_onclick() 
{
  if (document.form1.theDay.options[2].text != "Wednesday") 
  {
   var option = new Option("Wednesday",2);
   document.form1.theDay.options.add(option,2);
  }
  else 
  {
   alert('Do you want to have TWO Wednesdays?????');
  }
}

The remove() method takes just one parameter, namely the index of the option we want removed. When an option is removed, the options at higher index positions are moved down the array to fill the gap.

Using the remove() method, we can rewrite the butRemoveWed_onclick() function in our ch6_examp7.htm example to look like this:

function butRemoveWed_onclick() 
{
  if (document.form1.theDay.options[2].text == "Wednesday") 
  {
     document.form1.theDay.options.remove(2);
  } 
  else 
  {
   alert('There is no Wednesday here!');
  }
}

Modify the previous example and save it as ch6_examp8_IE.htm, before loading it into IE. You’ll see that it works just as the previous version did.

Continued…