最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change background color of a checkbox when checked with Jquery - Stack Overflow

programmeradmin0浏览0评论

I'm trying to change the background color of a div with a checkbox in it. I've made this / 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.

I'm trying to change the background color of a div with a checkbox in it. I've made this http://jsfiddle/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.

Share Improve this question asked Jul 10, 2012 at 23:24 VikramVikram 3493 gold badges7 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

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/Hmq65/

Working Demo http://jsfiddle/q3NN2/ or ANother way http://jsfiddle/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");
    }
});

Try this: http://jsfiddle/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;
}
发布评论

评论列表(0)

  1. 暂无评论