21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryでセレクトボックスの操作 

Last updated at Posted at 2013-01-19

ラジオボタンでセレクトボックスの中身を動的に変更しつつ、
offにチェックを入れた場合にはdisabledを設定し選択出来なくなるようにする。
また、offに設定された場合には全てvalue="0"の要素になるようにする。
「Aの項目でYESと答えないとBの項目は入力できない」なんて時に使える。

sample.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>Sample</title>
        <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <script src="./sample.js"></script>
        <style>
            .nodisp{ display: none; }
        </style>
    </head>
    <body>
        <form>
            <div>
            	<input type="radio" name="radio" value="1" checked="checked">on
            </div>
            <div>
            	<input type="radio" name="radio" value="0">off
            </div>
            <div>
            	<select id="select">
            	</select>
            </div>
            <div>
                <button type="submit">送信</button>
            </div>
        </form>
        <select id="select_hidden" class="nodisp">
            <option value="0">選択できません</option>
            <option value="1">選択肢1</option>
            <option value="2">選択肢2</option>
            <option value="3">選択肢3</option>
        </select>
    </body>
</html>
sample.js
$(function() {
    changeSelect();

    $("input[name=radio]").on('change', function() {
        changeSelect();
    });
});

function changeSelect() {
    $("#select").empty();
    $("#select").append($("#select_hidden option").clone());

    if ($("input[name=radio]:checked").val() == 1) {
        $("#select").val(1);
        $("#select option[value=0]").remove();
        $("#select").removeAttr("disabled");
    } else if ($("input[name=radio]:checked").val() == 0) {
        $("#select").attr("disabled", "disabled");
        $("#select").val(0);
    }
}
21
20
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
21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?