LoginSignup
7
10

More than 5 years have passed since last update.

(jQuery) clone()をテーブル作成で試す。

Posted at

clone()とは?

要素のコピーに使う。同じ内容のものを複製したいときなどに便利、行追加ができるテーブルを作ってみる。

サンプル

<!DOCTYPE html>
<html lang="ja">

<head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    $(document).ready(function(){
        var title = $("tr:first").clone();
        var input = $("tr:first").next().clone();

        $("#ap-add").click(function(){
            $(input).clone().appendTo("table");
        });

        $("#pre-add").click(function(){
            $("tr:first").remove();
            $(input).clone().prependTo("table");
            $(title).clone().prependTo("table");
        });

        $("#del").click(function(){
            $("td").parent().remove();
            $(input).clone().appendTo("table");
        });
    });
    </script>
</head>

<body>
    <div id="table">
        <table border=1>
            <tr>
                <th>チェック</th>
                <th>入力欄</th>
            </tr>
            <tr>
                <td>
                    <select name="sample">
                        <option value="A">A</option>
                        <option value="B">B</option>
                        <option value="C">C</option>
                    </select>
                </td>
                <td>
                    <input type="text">
                </td>
            </tr>
        </table>
    </div>
    <button id="ap-add">最後尾に追加</button>
    <button id="pre-add">先頭に追加</button>
    <button id="del">クリア</button>
</body>

</html>

htmlではテーブルと操作系のボタンを用意している。
以下、jQueryについての説明

var title = $("tr:first").clone();
var input = $("tr:first").next().clone();

ページを開くと同時に、titleとinputにそれぞれ項目行と入力行をクローンしている。これらを使って行の操作をおこなっている。

$("#ap-add").click(function(){
    $(input).clone().appendTo("table");
});

inputは入力行をそのままクローンしているので、テーブルの末尾に行を追加するにはappendTo("table")するだけ。

$("#pre-add").click(function(){
    $("tr:first").remove();
    $(input).clone().prependTo("table");
    $(title).clone().prependTo("table");
});

では先頭行に追加するにはどうするか。prependTo("table")すればいい、というほどシンプルではなく、それだけだと項目行より手前に入力行が追加されてしまう。そこでクローンしてるtitleの出番。
$("tr:first").remove()で項目行を一度削除してしまい、prependTo("table")で入力行、項目行の順に追加することで対応できる。

$("#del").click(function(){
    $("td").parent().remove();
    $(input).clone().appendTo("table");
});

$("td").parent().remove()で全ての入力行を削除し、その後に1行だけ入力行をappendTo("table")。これだけで初期の状態に戻すことができます。

7
10
3

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
7
10