James
James

Reputation: 2881

Highlight table row with checkbox using jQuery

I have the following HTML table. Each row contains a checkbox followed by some text.

<table>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Name</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Name2</td>
    </tr>
</table>

I need some help writing a script that will highlight (adding a class) the rows that have been checked and unchecking will remove that class.

Upvotes: 0

Views: 4599

Answers (6)

Ahmed Sherif
Ahmed Sherif

Reputation: 1

Worked for me

      $(document).on('click','tr',function(){
    if ($(this).css('background-color')=="rgb(143, 162, 225)") {

        $(this).find('input[type="checkbox"]').prop('checked',false);

        $(this).css('background','#ffffff'); 
    } else{
        $(this).find('input[type="checkbox"]').prop('checked',true);

        $(this).css('background','#8FA2E1'); `enter code here`
    }
});

Upvotes: 0

Sukanya1991
Sukanya1991

Reputation: 776

Check out this fiddle

JS

$(document).ready(function () {
    $("input:checkbox").change(function () {
        alert();
        if ($(this).prop("checked") == true) {
            $(this).closest('tr').addClass("checked");
        } else $(this).closest('tr').removeClass("checked");
    });
});

CSS

.checked {
    background-color:red;
}

Upvotes: 0

gaurang171
gaurang171

Reputation: 9090

http://codebins.com/codes/home/4ldqpb8

    $(":checkbox").change(function() {
        $(this).closest("tr").toggleClass("highlight", this.checked)
    })

Upvotes: 2

Mujah Maskey
Mujah Maskey

Reputation: 8804

$("#yourTableId input:checkbox").change(function() {
        var $this = $(this);
        if ($this.is(":checked")) {
            $this.closest("tr").addClass("highlight");
        } else {
            $this.closest("tr").removeClass("highlight");
        }
    });

Upvotes: 2

Tats_innit
Tats_innit

Reputation: 34117

Demo http://jsfiddle.net/328QV/

code

$(document).ready(function() {
    $("#Table input").click(function() {
        if ($(this).is(":checked")) {
            $(this).parent().parent().addClass("highlight");
        } else {
            $(this).parent().parent().removeClass("highlight");
        }
    });
});​

Upvotes: 0

elclanrs
elclanrs

Reputation: 94141

$('[type="checkbox"]').change(function(){
  $(this).parents('tr').toggleClass('highlight')
})

Upvotes: 0

Related Questions