Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tick a checkbox in a table cell by clicking anywhere in the table cell and change background color of that cell

Basically, I have a table with each cell containing a checkbox. I want to be able to tick the checkbox by clicking anywhere within the cell and change the color of that cell which I have done.

Now the problem is that when I tick the checkbox and then untick it, that cell is not getting that cell color back, as in the when the checkbox is unticked its cell color should be back to white. Can anyone help me? Help would be highly appreciated.

Here is my fiddle http://jsfiddle.net/UcDMW/50/

$(function () {
    $('table tr td').on('click', function (e) {
        if (e.target.type == "checkbox") {
            if ($(this).is(':checked')) {
                $(this).attr('checked', false);
                $(this).css('background-color', 'white');

            } else {
                $(this).attr('checked', true);
                $(this).css('background-color', '#DFF0D8');
            }
            return;
        } else {
            if ($(this).find('input:checkbox').is(':checked')) {
                $(this).css('background-color', 'white');

                $(this).find('input:checkbox').attr('checked', false);

            } else {
                $(this).find('input:checkbox').attr('checked', true);
                $(this).css('background-color', '#DFF0D8');

            }
        }
    });
});
like image 470
adward Avatar asked Jun 25 '14 08:06

adward


1 Answers

You can simply accomplish your task by the following snippet,

Try,

$('table tr td:has(:checkbox)').on('click', function (e) {
    $(this).toggleClass('className');
    if($(e.target).is(':checkbox')){ return; }
    var checked = $(this).find(':checkbox')[0].checked;
    $(this).find(':checkbox')[0].checked = !checked;
});

Cached version

$('table tr td:has(:checkbox)').on('click', function (e) {
    $(this).toggleClass('className');    
    if($(e.target).is(':checkbox')) return;
    var checkBox = $(this).find(':checkbox')[0];
    checkBox.checked = !checkBox.checked;
});

DEMO

like image 182
Rajaprabhu Aravindasamy Avatar answered Oct 09 '22 10:10

Rajaprabhu Aravindasamy