Beginning JavaScript | 16

11345
[previous] [next]

Beginning JavaScript

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.

<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>


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.

browser1

11345
[previous] [next]
and
Created: February 7, 2001
Revised: February 7, 2001

URL: http://webreference.com/programming/javascript/beginning/chap6/