Wed, 17/09/2008 - 22:08 — horuskol
A longstanding popular effect in forms are multiple selects – your choice in one select element (for example, a country) will cause a second select element to display a different list of options (states or counties).
The update of the second element is done using JavaScript:
var states = []; var states[0] = ['South Australia', 'New South Wales']; // Australia var states[1] = ['Cumbria', 'Berkshire']; // United Kingdom function change_state_select() { var nation_select = document.getElementById('nation_select'); var state_select = document.getElementById('state_select'); var selected_nation = nation_select.selectedIndex; while (state_select.options.length > 0) { // clears previous values from state selection list state_select.remove(0); } for (stateIdx in states[selected_nation]) { var new_opt = document.createElement('option'); new_opt.text = states[selected_nation][stateIdx]; new_opt.value = stateIdx; try { state_select.add(new_opt,null); // standards compliant - should work in most browsers but not IE } catch(e) { state_select.add(new_opt); // non-standard method - works in IE but not in most other browsers } } }
This script makes use of the try..catch statement of JavaScript – just give the above script with the following changes a try in IE, and you’ll see what try…catch is doing:
// try { state_select.add(new_opt,null); // standards compliant - should work in most browsers but not IE // } catch(e) { // state_select.add(new_opt); // non-standard method - works in IE but not in most other browsers // }
IE will not display errors, and the script won’t function – try…catch is normally used to trap errors in sequences of code and display the error message in a “friendly†way (as an alert, or a rewrite of some of the page’s content), or just enact some other alternative. In this case, the statement is being used to overcome the differences between standards compliant and non-compliant browsers.