A bit about

Hello, everyone! All you can see below is just my bank of information. Some material I've found in the fathomless net, some I've learned myself. Don't think all of the information here is right or actual, but may be it could be of use for you :) All feedback is welcome, especially constructive ones :)

Tuesday, February 24, 2009

Web: Dynamic dropdown lists

In order to change dropdown lists dynamically (depending on values of other elements) the current options of the list should be deleted and new options should be created. This code probably will be located in a handler function of another element (for example, another list or radio button).

For instance, if have 2 options - the first is type of numbers (1,2,3... or I, II, III...) and the second - actual number (it's just a model, I don't say that it's a very useful example :)). So the HTML code will be:
<form name="numbers">
<select name="num_type" onchange="num_type_change();">
<option value="1">1,2,3...</option>
<option value="I">I,II,III...</option>
<!-- remember option values from the previous post -->
</select>
<select name="num_value">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</form>

Now let's write a JavaScript function num_type_change() which will change the second list according to the selected type of numbers:
<Script language="JavaScript">
function num_type_change() {
var type = document.numbers.num_type.value;
var numbers_list = document.numbers.num_value;

// Reset options list
numbers_list.options.length = 0;

// Add required options
if (type == '1') {
numbers_list.options[0] = new Option('1','1');
numbers_list.options[1] = new Option('2','2');
numbers_list.options[2] = new Option('3','3');
numbers_list.options[3] = new Option('4','4');
}
else {
numbers_list.options[0] = new Option('I','I');
numbers_list.options[1] = new Option('II','II');
numbers_list.options[2] = new Option('III','III');
numbers_list.options[3] = new Option('IV','IV');
}
}
</Script>

0 comments:

Post a Comment