Liam neesan
Liam neesan

Reputation: 2561

How to set checkbox checked based on second column td is matched using JQuery?

I want to set checkbox is checked when second column record is matched. When record is matching with second column, it has to set the checkbox is checked for the same row.

$("#ContentPlaceHolder1_GridView1 tr td:nth-child(2)").each(function () {
                            //alert($(this).text());
    for(var i = 0;i<data.d.length;i++){
        if ($(this).text() === data.d[i]) {    // "222" === "222"
            alert('data =' + data.d[i] + '  $(this).text() = ' + $(this).text());

            //here I have to set checkbox
        }
    }
});

Here is my html code:

<table id="ContentPlaceHolder1_GridView1">
<tbody>
    <tr>
        <th> </th>                //No column header for checkbox
        <th>Documnet NO</th>
    </tr>
    <tr>
        <td><input id="Checkbox1" class="checkBoxClass" type="checkbox"></td>
        <td>111</td>
    </tr>
    <tr>
        <td><input id="Checkbox2" class="checkBoxClass" type="checkbox"></td>
        <td>222</td>
    </tr>
    <tr>
        <td><input id="Checkbox3" class="checkBoxClass" type="checkbox"></td>
        <td>333</td>
    </tr>
</body>

until now the matching record of alert is working

Upvotes: 0

Views: 553

Answers (2)

Satpal
Satpal

Reputation: 133423

You can use DOM traversal method to target :checkbox, then use .prop(key, value) to set its property

$("#ContentPlaceHolder1_GridView1 tr td:nth-child(2)").each(function () {
    for (var i = 0; i < data.d.length; i++) {
        if ($(this).text() === data.d[i]) {
            $(this).closest('tr') //target common parent i.e. TR
            .find(':checkbox') //Target Checkbox
            .prop('checked', true);
        }
    }
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

$(this) refers to context of td element. you can

1) find sibling td elements

2) find input element in td

3) set checkbox checked state as true

$("#ContentPlaceHolder1_GridView1 tr td:nth-child(2)").each(function () {
 for(var i = 0;i<data.d.length;i++){
    if ($(this).text() === data.d[i]) {     
       $(this).siblings().find(':checkbox').prop('checked' , true);
    }
});

Note: Also you have got duplicate IDs for input elements. IDs must be unique. You can not target multiple elements using same ID using id selectors. You can rather use common class along with class selector to target them all.

Upvotes: 0

Related Questions