【Javascript】selectタグの選択で別のselectタグのメニュー項目を変更

Javascriptでselectタグの選択肢によって、別のselectタグのメニュー項目を変更する方法をソースコード付きでまとめました。

## selectタグの選択で別のselectタグのメニュー項目を変更

Javascriptでselectタグの選択肢によって、別のselectタグのメニュー項目を変更します。

## サンプルコード

サンプルプログラムのソースコードです。

Javascript

js/main.js

function initSelect(){
    var select1 = document.forms.formName.select1;
    var select2 = document.forms.formName.select2;
    select2.options.length = 0;

    if (select1.options[select1.selectedIndex].value == "1")
    {
        select2.options[0] = new Option("1-1");
        select2.options[1] = new Option("1-2");
        select2.options[2] = new Option("1-3");
    }else if (select1.options[select1.selectedIndex].value == "2")
    {
        select2.options[0] = new Option("2-1");
        select2.options[1] = new Option("2-2");
        select2.options[2] = new Option("2-3");
    }else if (select1.options[select1.selectedIndex].value == "3")
    {
        select2.options[0] = new Option("3-1");
        select2.options[1] = new Option("3-2");
        select2.options[2] = new Option("3-3");
    }
};

window.onload = function() {
    var select1 = document.forms.formName.select1;
    select1.options[0] = new Option("1");
    select1.options[1] = new Option("2");
    select1.options[2] = new Option("3");

    document.getElementById("select1").onclick = function() {
        initSelect();
    };

};

HTML

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TEST</title>
<pre title="http://code.jquery.com/jquery-1.11.1.js"></pre>
<pre title="js/main.js"></pre>
</head>
<body>
    <form name="formName" method="post" action="./pathToProgramFile">
        <!-- 選択肢1-->
        <select name = "select1" id="select1">
        </select>

        <!-- 選択肢2(選択肢1で選んだ項目で変化)-->
        <select name = "select2">
        </select>
</body>
</html>
関連ページ
1 【Vue.js入門】使い方・サンプル集
2 Javascript入門 サンプル集
3 Node.js入門
Javascript
スポンサーリンク

コメント