サイトアイコン 知的好奇心

jqueryでチェックされた項目をループ処理で取得する方法

jqueryでチェックされた項目をループ処理で取得する方法をご紹介します。

条件

概要

以下のようなテーブルで、「チェック項目」というボタンを押した際、
チェックした項目を取得する処理を考えます。

ソース

以下はサンプルソースです。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
  <meta charset="utf-8" />
</head>
<body>
  <h1>チェック項目の取得</h1>
  <table border="1" id="targetTable">
    <thead>
    <tr>
      <th>チェック</th>
      <th width="50px">名前</th>
      <th width="50px">年齢</th>
    </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox" id="id1"></td>
        <td class="name">佐藤</td>
        <td class="age">131</td>
      </tr>
      <tr>
        <td><input type="checkbox" id="id2"></td>
        <td class="name">鈴木</td>
        <td class="age">157</td>
      </tr>
    <tbody>
  </table>
  <br />
  <button id="js-btn">チェック項目</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
  <script>
    $(function(){
      const btn = $("#js-btn");
      btn.click(function () {

        var selectedIds = new Array();
        $('#targetTable input[type="checkbox"]:checked').each(function() {
            selectedIds.push($(this).attr('id'));
        });
        console.log('クリックされたID:' + selectedIds);
        //alert('クリックされたID:' + selectedIds);
        
        var selectedItems = new Array();
        $('#targetTable input[type="checkbox"]').each(function(checkedIndex) {
          if(this.checked){ // チェックされているのも
            selectedItems.push($('.name').eq(checkedIndex).html());
          }
        });
        console.log('クリックされた項目:' + selectedItems);
        //alert('クリックされた項目:' + selectedItems);
      });
    });
  </script>
</body>
</html>

ポイント

実行結果

以下は、Edgeの開発者ツールでコンソール出力を確認した結果です。
ボタンを押した際、「チェックしたID」および「名前」の項目が取得出来ていることが分かります。

参考

TechAcademyマガジン:JavaScriptでtableの値を取得する方法を現役エンジニアが解説【初心者向け】

JavaScriptでtableの値を取得する方法を現役エンジニアが解説【初心者向け】

stackoverflow:Jquery how to select checked checkboxes from a html table

https://stackoverflow.com/questions/22086158/jquery-how-to-select-checked-checkboxes-from-a-html-table

SAMURAI TERAKOYA:【jQuery入門】eq()の使い方とインデックス番号の活用法!

【jQuery入門】eq()の使い方とインデックス番号の活用法!

モバイルバージョンを終了