JavaScriptプログラムに関する各種メモ書き

ドロップダウンリストの状態をJavaScriptで動的に変更する

ドロップダウンリスト(オプションメニュー)の状態をJavaScriptで動的に変更する

<select id="prefecture_id" name="prefecture_name" >
<option value="北海道">北海道</option>
<option value="沖縄">沖縄</option>
</select>

● 関数名(_change_dropdown_id)

function _change_dropdown_id( id_name, value ){
	var element = document.getElementById(id_name);
	if (! element){ alert( '<select id="' + id_name +'"> is not find.'); return; }	
	var flag = false;
	for (var i=0; i<element.options.length; i++) {
		var option = element.options[i];
		if (option.value == value){
			if (flag){
				option.selected = false;
			}
			else{
				option.selected = true; flag = true;
			}
		}
		else{ option.selected = false; }
	}
	if(! flag){ alert( 'DATA [' + value + '] is not find in <select id="'+id_name+'"> '); }
}

● 関数名(_change_dropdown_name)

function _change_dropdown_name( form_name, value ){
    var element = window.document.getElementsByName(form_name)[0];
    if (! element){ alert( '<select id="' + id_name +'"> is not find.'); return; }
    var flag = false;
    for (var i=0; i<element.options.length; i++) {
        var option = element.options[i];
        if (option.value == value){
            if (flag){
                option.selected = false;
            }
            else{
                option.selected = true; flag = true;
            }
        }
        else{ option.selected = false; }
    }
    if(! flag){ alert( 'DATA [' + value + '] is not find in <select id="'+id_name+'"> '); }
}

● Usage(使い方)

// IDでの呼び出し
_change_dropdown_id( 'prefecture_id', '沖縄' );
// フォーム名での呼び出し
_change_dropdown_name( 'prefecture_name', '沖縄' );

ちなみに ドロップダウンリストを 操作できないような状態にするには

document.getElementById('prefecture').disabled = true; // 操作不可能にする
document.getElementById('prefecture').disabled = false; // 操作可能にする 
No.592
06/15 18:24

edit