表データの選択制御第二回は列と行の制御です。列と行をjQueryを使って一括制御します。
○第一回:全選択の制御
○第二回:列と行の選択制御 ←今回の説明内容
○第三回:個別セルの選択制御
以下制御のサンプルソースです。
第二回:列と行の制御
htmlとcssサンプルのソースは前回のものから若干の修正・追加をします。
<table style="width: 100%;"> <thead> <tr> <th id="all">全て選択</th> <th class="row">選択↓</th> <th class="row">選択↓</th> <th class="row">選択↓</th> </tr> </thead> <tr> <th class="col">選択→</th> <td>リンゴ</td> <td>ぞう</td> <td>バラ</td> </tr> <tr> <th class="col">選択→</th> <td>バナナ</td> <td>ゴリラ</td> <td>チューリップ</td> </tr> <tr> <th class="col">選択→</th> <td>もも</td> <td>パンダ</td> <td>パンジー</td> </tr> </table>
■css
.td_chk { background: red; } #all,.row,.col { text-decoration: underline; cursor: pointer; }
javascriptは前回の全選択制御に追加で列と行の制御を加えます。
■javascript
$(function() { //全選択 $("#all").toggle( function() { $(this).text('全て解除'); $(this).parent().parent().parent().find('td').each(function() { $(this).addClass('td_chk'); }); }, function() { $(this).text('全て選択'); $(this).parent().parent().parent().find('td').each(function() { $(this).removeClass('td_chk'); }); }); //列の選択 $(".row").toggle( function() { $(this).text('解除↓'); var num = $(".row").index(this); $("#sample tbody tr").each(function() { $(this).find("td").eq(num).addClass('td_chk'); }); }, function() { $(this).text('選択↓'); var num = $(".row").index(this); $("#sample tbody tr").each(function() { $(this).find("td").eq(num).removeClass('td_chk'); }); }); //行の選択 $(".col").toggle( function() { $(this).text('解除→'); $(this).parent().find('td').each(function() { $(this).addClass('td_chk'); }); }, function() { $(this).text('選択→'); $(this).parent().find('td').each(function() { $(this).removeClass('td_chk'); }); }); });
解説
今回は列と行を一括選択・解除するハンドラとしてclass「row」と「col」を用意しました。
class「row」をクリックするとクリックした列を一括選択し、class「col」をクリックすると行を一括で選択します。
まずは列の選択です。
//行の選択 $(".row").toggle( function() { $(this).text('解除↓'); var num = $(".row").index(this); $("#sample tbody tr").each(function() { $(this).find("td").eq(num).addClass('td_chk'); }); }, function() { $(this).text('選択↓'); var num = $(".row").index(this); $("#sample tbody tr").each(function() { $(this).find("td").eq(num).removeClass('td_chk'); }); });
クリックした列を判別する為に変数「num」にクリックされた列の番号を格納し、eachでtr枚に「num」番目のtdにclass「td_chk」をaddClassで追加していきます。
解除も同様です。
行の選択・解除はもっとシンプルで、以下のようにクリックされたclass「col」の親(tr要素)からfindでtd要素をが見つかるたびにaddClassでtdに対してclass「td_chk」を追加していきます。
$(function() { //行の選択 $(".col").toggle( function() { $(this).text('解除→'); $(this).parent().find('td').each(function() { $(this).addClass('td_chk'); }); }, function() { $(this).text('選択→'); $(this).parent().find('td').each(function() { $(this).removeClass('td_chk'); }); });
前回のセルの全選択・全解除に続き、列と行の制御も実装できたかと思います。
最後は、セル単体の選択・解除を実装したいと思います。
○第三回:個別セルの選択制御