Search

12/27/2007

scripting select and option

http://chunghe.googlepages.com/select.htm
在select中選擇發生的事件是 onchange, foo.selectedIndex 可以抓到選取項目的 index, 從 0 開始, foo.options[foo.selectedIndex]可以抓取項目的 reference, foo.options[foo.selectedIndex].value可以抓到選取項目的 value, bar.options[i].selected = true 可以選取第 i 項 option

var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var mapping = {
'programming': 'a',
'surfing' : 'd',
'caffeine' : 'b',
'annoying_ohoh' : 'c',
'thinking' : 'x'
}
foo.onchange = function(){
// get the value of selected item
var selectedValue = foo.options[foo.selectedIndex].value;
if('undefined' === typeof mapping[selectedValue]){
alert(selectedValue + ': no such item');
return
}

// map the select value to another select
var mappingValue = mapping[selectedValue];

// search select 'bar' for the mappingValue
var options = bar.getElementsByTagName('option');
for(var i=0; i<options.length; i++){
if(options[i].value == mappingValue){
bar.options[i].selected = true;
break;
}
}
if(options.length == i){
alert(foo.options[foo.selectedIndex].value + ': no match');
}
}

沒有留言: