2012年1月20日金曜日

table のチェックボックスをクリックしたときに行の背景色を変える

HTML:例
<table>
    <tr>
         <td><input type="checkbox" id="test_0" name="test[]" class="test" value="mo1"></td>
         <td>TEST1</td>
    </tr>
    <tr>
         <td><input type="checkbox" id="test_1" name="test[]" class="test" value="mo1"></td>
         <td>TEST2</td>
    </tr>
    <tr>
         <td><input type="checkbox" id="test_2" name="test[]" class="test" value="mo1"></td>
         <td>TEST3</td>
    </tr>
</table>
CSS:例
    /* チェックボックスにチェックを入れた際の背景色 */
    .tr-selected { background-color:#fcc; }

■jQuery:例

<script language="javascript">
    $('.selected_id').click(function(){
        if($(this).attr("checked")){
            $(this).attr('checked', true);
            $(this).parent().parent().addClass("tr-selected");
        }
        else{
            $(this).attr('checked', false);
            $(this).parent().parent().removeClass("tr-selected");
        }
   }
</script>