LoginSignup
0
0

More than 1 year has passed since last update.

jQueryのparentを使ってテーブルの背景色を操作してみる

Posted at

やりたいこと

元々あるこちらのテーブル内のチェックボックスを付けると色を加えるように変更したい。
sample.png

こんな感じにしたい。
sample2.png

使用言語

  • PHP7.0
  • jQuery
  • CSS

実装

チェックボックスに対し、checkClassクラス, trタグにcheckClass2クラスを付与する。

sample.ctp
<table>
<tbody>
	<tr class="checkClass2">
    <td rowspan="3">
    <?php
       $checkAttr = array(
            'class' => 'checkClass',
            'div' => false);
    echo $this->Form->input('xxx.Id.', $checkAttr);
    ?>
</td>
</tbody>
</table>

チェックボックスにチェックが付けられた時の挙動を制御する。
チェックボックスが付けられた状態はthisである。従ってチェックボックスが付けられたタグの一階層上はtdタグ、もう一階層上にはtrタグがあるためparentでそれらを取得する。
そして背景色変更用のクラスをaddClassで加える。

sample.js
$('.checkClass').change(function() {
    if ($(this).prop('checked')) {
        $(this).parent().parent().find("td").addClass("check1");
    } else {
        $(this).parent().parent().find("td").removeClass("check1");
    }    
})

背景色変更用のクラスの操作内容をCSSで定義する。

sample.css
.check1 {
    background: yellow !important;
}

これで終わり。

0
0
1

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