user1028428
user1028428

Reputation: 81

Set td background color in jquery when td id's are known

I have a jquery function which gets the id value of td's whose checkboxes are checked. I need to color those td's. I have written this function which does not give me any error but does not color the td's also..

Here is the function:

$('#custom-interval-tbl td').each(function() {
 $(this).find('input:checkbox:checked').each(function() {      
    var tdId= $(this).attr("id");
    var tdElement = $("#custom-interval-tbl td").eq(tdId); 
    console.log("TD Element"+tdElement);        
    tdElement.css({background:"#333333"});
    });
});

Can someone please tell me what mistake am I doing?

Thanks for your help.

Upvotes: 1

Views: 1410

Answers (2)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67191

jsFiddle DEMO

The problem is you're using .eq() (which is index-based), but you're giving it the id of the checkbox.

On a side note, don't use :text / :checkbox / etc, these are deprecated within jQuery, and it is better to use native [type="checkbox"], etc.

$('#custom-interval-tbl td').each(function() {
    $(this).find('input[type="checkbox"]:checked').each(function() {
        // You don't need to find out ID or anything.
        // Just go up to the closest <td> and give it the background

        var tdElement = $(this).closest('td');     
        tdElement.css({ background : "#333333" });
    });
});​

Upvotes: 1

Chris
Chris

Reputation: 26918

I think the problem here is that this inside the second function refers to the checkbox, not to the td. Try this:

$('#custom-interval-tbl td').each(function() {
 $(this).find('input:checkbox:checked').each(function() {      
    var tdElement = $(this).parent("td");
    console.log("TD Element"+tdElement);        
    tdElement.css({background:"#333333"});
    });
});

Upvotes: 1

Related Questions