简体   繁体   中英

Change background color of a checkbox when checked with Jquery

I'm trying to change the background color of a div with a checkbox in it. I've made this http://jsfiddle.net/B7P65/ for reference. I'm trying to replace the parent div with the 'highlight' div, so i thought the toggle div would work. When the checkbox is deselected, I would like the background color to go back to normal (or remove the 'highlight' div). Any help is appreciated.

You are using the parent() method incorrectly. You want to extract the toggleClass() method from within the parent() method and place it separately.

Try the following update:

$(this).parent().toggleClass("highlight");

Complete:

$("input:checkbox").click(function() {
    var actualTime = "";
    $(this).parent().toggleClass("highlight");
});

Demo: http://jsfiddle.net/Hmq65/

Working Demo http://jsfiddle.net/q3NN2/ or ANother way http://jsfiddle.net/KUhFp/

second demo shows how to use using .is(':checked') just something extra if you want to use the is checked logic, :)

code

$("input:checkbox").click(function() {
    var actualTime = "";
    $(this).parent().toggleClass("highlight");
});

code

$("input:checkbox").click(function() {
    var actualTime = "";
    if ($(this).is(':checked')) {
        $(this).parent().addClass("highlight");

    } else {
        $(this).parent().removeClass("highlight");
    }
});

试试这个: http : //jsfiddle.net/B7P65/1/

This code works for highlighting when checked and remove class when unchecked.

JavaScript:

    $('#your table id tr')
    .filter(':has(:checkbox:checked)')
    .addClass('highlight')
    .end()
    .click(function(event) {
        $(this).toggleClass('highlight');
    if (event.target.type !== 'checkbox') {
        $(':checkbox', this).attr('checked', function() {
        return !this.checked;
    });
  }
});

CSS:

.highlight{
    background-color:green;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM