2
3

More than 1 year has passed since last update.

テーブル内チェックボックスのクリック範囲拡大方法

Posted at

テーブル内チェックボックスのクリック範囲拡大方法

イメージ

このようなイメージのサンプルを作成してみたので、共有したいなと思います。

sample

ポイント

  • td要素をクリックしたときにcheckboxをクリックするjsイベントを作成
  • バブリングを防止

サンプルコード

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <style type="text/css">
        .pointer, #test_1, #test_2 {
            cursor: pointer;
        }
    </style>
    <title>click test</title>
  </head>
  <body>
    <table border="1">
        <tr>
            <th width='200px'></th>
            <th>名前</th>
            <th>年齢</th>
        </tr>
        <tr class='box'>
            <td class='pointer'><input type="checkbox" id="test_1"></td>
            <td>田中</td>
            <td>27</td>
        </tr>
        <tr class='box'>
            <td class='pointer'><input type="checkbox" id="test_2"></td>
            <td>佐藤</td>
            <td>42</td>
        </tr>
    </table>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">

        // チェックボックスを含む td 要素をクリックしたときに、チェックボックスをクリック
        $('td:has(input[type=checkbox])').on('click', function(e){
            $(this).find('input[type=checkbox]').click();
        });
        // バブリングを防止
        $('td input[type=checkbox]').on('click', function(e){
            e.stopPropagation();
        });

      </script>
  </body>
</html>

参考

2
3
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
2
3