Phillip Senn
Phillip Senn

Reputation: 47663

jQuery sibling selector

I have the following:

<input name="Check100" type="checkbox">
<tr>
   <td><input name="ClassIDs" type="checkbox" value="3132">
   <td>50</td>
</tr>
<tr>
   <td><input name="ClassIDs" type="checkbox" value="3133">
   <td>100</td>
</tr>

<script>
$('input[name=Check100]').change(function() {
var myChecked = $(this).attr('checked');
$('input:checkbox').attr('checked',myChecked);
});
</script>

But what I need to do is toggle all the inputs that have a 100 in column 2.

Upvotes: 0

Views: 1291

Answers (2)

Peter &#214;rneholm
Peter &#214;rneholm

Reputation: 2858

I first thought of using :contains() but when I read the documenation i realized that it checks for exactly what it says, if it contains something, not the exact match. I didn't find any shorthand function for this, but you can use filter().

For example, :contains('100') will also match 1000.

Code:

$('input[name=Check100]').change(function() {
    var myChecked = $(this).attr('checked');

    $('td').filter(function() {
        return $(this).text() == "100";
    }).prev('td').find(':checkbox').attr('checked', myChecked);
});

Example: http://jsfiddle.net/FEP5u/

Update:

Enhanced version: http://jsfiddle.net/FEP5u/2/

Using IDs at your elements and as your selectors improves the speed. And the HTML spec says (I think) that attributes like checked should be removed instead of being set to false.

HTML:

<input name="Check100" id="Check100" type="checkbox">
<table id="myTable">
    <tr>
        <td><input name="ClassIDs" type="checkbox" value="3132"></td>
        <td>50</td>
    </tr>
    <tr>
        <td><input name="ClassIDs" type="checkbox" value="3133"></td>
        <td>1000</td>
    </tr>
    <tr>
        <td><input name="ClassIDs" type="checkbox" value="3134"></td>
        <td>100</td>
    </tr>
</table>

Javascript:

$(function(){
    $('#Check100').change(function() {
        var $checkbox = $('#myTable td')
            .filter(function() {
                return $(this).text() == "100";
            }).prev('td').find(':checkbox');

        if(this.checked)
            $checkbox.attr('checked', 'checked');
        else
            $checkbox.removeAttr('checked');
    });
});

Upvotes: 2

PetersenDidIt
PetersenDidIt

Reputation: 25620

Try this:

$('input[name=Check100]').change(function() {
    var myChecked = $(this).attr('checked');
    $('td:contains(100)').prev('td').find(':checkbox').attr('checked', myChecked);
});

Example: http://jsfiddle.net/petersendidit/NLJQd/

Upvotes: 1

Related Questions