LoginSignup
0
1

More than 3 years have passed since last update.

JavaScriptで2段階に連動するプルダウンの作成と要素の表示、非表示

Last updated at Posted at 2020-11-21

備忘録として残しておきます

HTML

choice.html
<select id="parent" onchange="date()" class="form">
  <option value="和食">和食</option>
  <option value="洋食">洋食</option>
  <option value="中華">中華</option>
  <option value="" disabled selected>選択してください</option>
</select>

<select id="children" class="form">
  <option value="" disabled selected>選択してください</option>
  <option value="味噌汁">味噌汁</option>
  <option value="肉じゃが">肉じゃが</option>
  <option value="天ぷら">天ぷら</option>

  <option value="グラタン">グラタン</option>
  <option value="オムライス">オムライス</option>
  <option value="ナポリタン">ナポリタン</option>

  <option value="麻婆豆腐">麻婆豆腐</option>
  <option value="餃子">餃子</option>
  <option value="春巻">春巻</option>
</select>

CSS

choice2.css
#children option:disabled{
  display:none;
}
#children option{
  display:block;
}

JavaScript

choice3.js
function date() {

//id="parent"の値を取得
var parentlement = document.getElementById( "parent" ) ;

//id="children"を取得
var childrenDate = document.getElementById("children") ;

   //disabledをtrueに
  for (var i = 0; i < childrenDate.length; i++){
       childrenDate.options[i].disabled = true;
  }
    // disabledに代入
     if( parentlement.value == "和食") {
       childrenDate.options[1].disabled = false;//味噌汁
       childrenDate.options[2].disabled = false;//肉じゃが
       childrenDate.options[3].disabled = false;//天ぷら

    } else if( parentlement.value == "洋食") {
       childrenDate.options[4].disabled = false;//グラタン
       childrenDate.options[5].disabled = false;//オムライス
       childrenDate.options[6].disabled = false;//ナポリタン

    } else if ( parentlement.value == "中華") {
       childrenDate.options[7].disabled = false;//麻婆豆腐
       childrenDate.options[8].disabled = false;//餃子
       childrenDate.options[9].disabled = false;//春巻

     } else if ( parentlement.value = "") {
       childrenDate.disabled = true;
    }
}

和食を選択します。
スクリーンショット (35).png
和食を選択すると「味噌汁」「肉じゃが」「天ぷら」以外にdisabledが付きます。

disabledが付いたoptionは非表示になります。

choice2.css
#children option:disabled{
  display:none;
}

display:none;がなければこうなります。↓
スクリーンショット (38).png

まとめ

このやり方でも一応動きますが、これではメンテナンスがしにくいのでJavaScriptの改善が必要みたいです。

参考リンク

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1