0
0

More than 3 years have passed since last update.

js table操作

Posted at
<html>

<head>
<title>title</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th><input id="all" type="checkbox" onclick="all()" />check</th>
                <th>id</th>
                <th>name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input name="chk[]" type="checkbox" checked /></td>
                <!--                <td><input type="checkbox" /></td> -->
                <td>1</td>
                <td>sample1</td>
            </tr>
            <tr>
                <td><input name="chk[]" type="checkbox" /></td>
                <!--                <td><input type="checkbox" /></td> -->
                <td>2</td>
                <td>sample2</td>
            </tr>
            <tr>
                <td><input name="chk[]" type="checkbox" checked /></td>
                <!--                <td><input type="checkbox" /></td> -->
                <td>3</td>
                <td>sample3</td>
            </tr>
        </tbody>
    </table>
    <button type="submit" onclick="go()">go</button>
</body>
<script type="text/javascript">
    function changeHeader() {
        // tbody以下のチェックボックスとtbody以下のinput要素数が同じか判定
        if ($('tbody :checked').length == $('tbody :input').length) {
            // 全てのチェックボックスにチェックが入っている場合
            $('#all').prop('checked', true); // 「全選択」 = checked
        } else {
            $('#all').prop('checked', false); // 「全選択」 = not checked
        }
    }

    function go() {
        // tbody以下のtr以下の1つ目のtdの値をリスト化
        let list = [];
        $("tbody tr").each(function(i) {
            // checkedの状態か判定
            if ($(this).find("input").prop("checked")) {
                list.push($(this).find("td").eq(1).text());
            }
        })
        console.log(list);
    }

    // 1. 「全選択」する
    $('#all').on('click', function() {
        $("tbody :input").prop('checked', this.checked);
    });
    // 2. 「全選択」以外のチェックボックスがクリックされたら、
    $("input[name='chk[]']").on('click', function() {
        changeHeader();
    });

    // 画面ロード時のfunction
    $(function() {
        changeHeader();
    });
</script>
</html>
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