LoginSignup
14
21

More than 5 years have passed since last update.

jQueryでselect要素のoptionを非表示にする

Posted at

やりたいこと

select要素のoptionを条件により表示・非表示させたい

例えば、他にselect要素があり、そちらで選択された値に応じてもう1つの方のselect要素のoptionを表示・非表示させたいというケースなどです。
ちなみに、はじめはoptionにdisplay:noneとしようとしたのですが、IEなどではoptionにdisplay:noneができないことがわかり、別の方法で実装しました。
その実装方法の一例です。

コード

catsList.html
<select id="list">
  <option class="cats" value="blackcat">Black Cat</option>
  <option class="cats" value="whitecat">White Cat</option>
  <option class="cats" value="calicocat">Calico Cat</option>
  <option class="cats" value="americanshorthair">American Shorthair</option>
  <option class="cats" value="russianblue">Russian Blue</option>
  <option class="cats" value="abyssinian">Abyssinian</option>
  <option class="cats" value="siamese">Siamese</option>
</select>
catsList.js
$('.cats').each(function(index) {
  const type = $(this).val();
  const wrap = $(this).parents().attr("class");
  //White Catを非表示
  if(type == "whitecat"){  
    //現在表示中の場合  
    if(wrap !== "wrap"){
      $(this).wrap("<span class='wrap'>");
    }
  }
  //Black Catを表示
  if(type == "blackcat"){
    //現在非表示中の場合
    if(wrap == "wrap"){
      $(this).unwrap();
    }
  }
});

上記のように<option></option><span class='wrap'></span>で囲うことで非表示にできます。
反対に、<span class='wrap'></span>を取り除くと表示されます。
なお、非表示中の場合は以下のhtmlになります。

catsList.html
  <span class="wrap"><option class="cats" value="whitecat">White Cat</option></span>
14
21
0

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
14
21