LoginSignup
16
12

More than 5 years have passed since last update.

セレクトボックスで選択されていない要素を動的にdisabledする

Posted at

あまり使う機会が無いかもしれませんが。
主にPHPを使ってデータ変更をする時を想定しています。
データ変更時に権限がないと変更出来ない部分を作りたいけど、selectをdisabledにしてしまうと
selectがPOSTされないので若干面倒くさいことになったりします。

そういうときはselected以外のoptionをdisabledにしてしまえば解決します。

<select id="sample" name="sample">
    <option value="0">選択肢1</option>
    <option value="1" selected>選択肢2</option>
    <option value="2">選択肢3</option>
</select>
$(function(){
    // 画面表示時にselected以外をdisableにする
    $("#sample option:not(:selected)").prop('disabled', true);
});

<select id="sample" name="sample">
    <option value="0" disabled>選択肢1</option>
    <option value="1" selected>選択肢2</option>
    <option value="2" disabled>選択肢3</option>
</select>

これでPOSTした時にきちんとsampleの値を送れるし、選択肢を変更することも出来なくなりました。
あとは何らかの条件が成立した時(sessionを見て管理者でログインしていれば、等)に
$("#sample option:not(:selected)").prop('disabled', false)としてやれば全て選択できるようになります。

selectedを動的に出すのはよくやりますが、それ以外をdisabledにするとなるとjQueryとかを使ったほうが楽ですね。

16
12
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
16
12