jqueryでチェックされた項目をループ処理で取得する方法
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>
ポイント
- 以下のような記述で、”チェックボックス”かつ”チェックされている”ものを取得し、
ループ処理を行うことが出来ます。
$(‘#targetTable input[type=”checkbox”]:checked’).each(function() { - 以下のような記述で、”チェックボックス”のループ処理を行い、
if文でチェックされた項目のみを判定することが出来ます。
$(‘#targetTable input[type=”checkbox”]’).each(function(checkedIndex) {
if(this.checked){ - 以下のような記述で、項目のインデックスを指定してタグの中身を取得することが出来ます。
$(‘.name’).eq(checkedIndex).html()
実行結果
以下は、Edgeの開発者ツールでコンソール出力を確認した結果です。
ボタンを押した際、「チェックしたID」および「名前」の項目が取得出来ていることが分かります。




