0

I would like to use the classnames of table cells to check checkboxes of the corresponding value, using jQuery. I don't know if I need to use eval or something similar.

Code:

<p style="float:right;">
These columns are visible: 
<br/><input type="checkbox" name="vehicle" value="col1" /> Col1
<br/><input type="checkbox" name="vehicle" value="col2" /> Col2
<br/><input type="checkbox" name="vehicle" value="col3" /> Col3
</p>
<table id="comptable">
<tr> 
<td class="col1">Col1</td>
<td class="col2" style="display:none;">Col2</td>
<td class="col3">Col3</td>
</tr>
</table>
$(document).ready(function(){
    var visible_tds = $('comptable td:visible');
    // Check the checkboxes that correspond to the visible table cells.
    $.each(visible_tds, function() { 
       // use ($(this).attr('class'))
       // to check the checkbox?
    });
});

JSFiddle: http://jsfiddle.net/TJ3zN/5/

2 Answers 2

2

You can do it like this:

$(document).ready(function(){
    // Check the checkboxes that correspond to the visible ones
    $('#comptable td:visible').each(function() { 
        $("input[value='" + $(this).attr('class') + "']").attr('checked', true);
    });
});

The input[value=''] selector will return any inputs with the attribute value that matches whatever you specify inbetween the '' marks.

You were also missing a # from the beginning of your the compatable selector. The table has the ID of compatable so to select an ID you have to put a # before it.

1
$(document).ready(function(){
    $('#comptable td:visible').each(function() {
       $("input[type=checkbox][value='" + $(this).attr("class") + "']").prop("checked", true);
    });
});

That should do the trick. It finds the checkbox with value equal to the value of the class attribute of each visible td, and set the checked property to true (note that you will have to be using jQuery 1.6 at least to use the prop function, otherwise, you'll have to use attr).

You can see it running here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.