LoginSignup
0
0

More than 3 years have passed since last update.

jQueryでセレクトボックスの選択要素を移動する

Last updated at Posted at 2020-09-26

二つセレクトボックス(Selectタグ)があるサイトで、片方のセレクトボックスの選択要素を別のセレクトボックスに移動させるメモ

移動元の指定をoption:selectedにするのがミソ
$("#移動元SelectタグのID option:selected").appendTo($("#移動先SelectタグのID"));

移動ではなくコピーしたいときはclone()を挟むだけ
$("#コピー元SelectタグのID option:selected").clone().appendTo($("#コピー先SelectタグのID"));

Sample

html部分
<!-- 移動元 Selct Tag-->
<select id="selectFrom" size="10">
    <option value="1">りんご</option>
    <option value="2">みかん</option>
    <option value="3">なし</option>
    <option value="4">いちご</option>
</select>

<!-- 移動先 Selct Tag-->
<select id="selectTo" size="10">
    <option value="5">ぶどう</option>
</select>

<!-- 実行ボタン-->
<input type="button" id="move" value="->" />
javascript部分
<script type="text/javascript">
    $(function () {
        $("#move").on("click", function () {
            // 移動元のSelectから移動先のSelectに移動
            $("#selectFrom option:selected").appendTo($("#selectTo"));

            // 移動ではなくコピーしたいときはclone()を挟むだけ
            // $("#selectFrom option:selected").clone().appendTo($("#selectTo"));
        });
    });
</script>
0
0
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
0
0