Controlling Data Entry Using Form Fields
Creating 'Encoded' Name & Value Pairs
Passing data from one form to another
Addressing Form Field Validation with Regular Expressions and JavaScript 1.2
You are here: irt.org | Articles | JavaScript | Form | Chapter 6: Beginning JavaScript [ previous next ]
Published on: Sunday 29th April 2001 By: Paul Wilton
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.
Controlling Data Entry Using Form Fields
Creating 'Encoded' Name & Value Pairs
Passing data from one form to another
Addressing Form Field Validation with Regular Expressions and JavaScript 1.2