Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues selecting class in table

Tags:

jquery

I am just diving into jquery, so please excuse any really silly mistakes...

I have a table I am generating from a database.

<table id="DataTable">
    <tr>
        <th><input type="button" onclick=doCheck()></th>
        <th>col 2</th>
        <th>col 3</th>
        <th>col 4</th>
        <th>col 5</th>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>data 2</td>
        <td>data 3</td>
        <td>data 4</td>
        <td class="thisOne">data 5</td>
    </tr>
 .
 .
 .
  </table>

I need to perform some validation checks on column5, labeled thisOne, based on whether or not it is in a row where the box is checked. Here is what I have so far:

//Get checkboxes
var boxes = $("#DataTable").find("tr td input[type=checkbox]");
var locations = [];
boxes.each(function (index, element) {
        if ($(element).is(':checked')) {
            //Code here
        }
    });

In the area marked //code here I have tried many things and have not been able to successfully select the column I want. Some things I have tried (NOTE: I am using Hide() for testing purposes):

$(this).closest("td").next('.thisOne').hide(); Doesn't work
$(this).parent("td").next('.thisOne').hide();  Doesn't Work
$(this).closest("td").hide();                  Works as expected
$(this).closest("td").next().hide();           Works as expected
$('.thisOne').hide();                          Works as expected

Shouldn't the first line I listed work? .closest() will navigate up to the td level, where .next('thisOne') will traverse the DOM until a td tag with that class is found? Please explain any answers as I am really curious as to why this is not working. Thanks

like image 310
Jeff Avatar asked Dec 20 '25 05:12

Jeff


2 Answers

What you need is .siblings()

$(this).closest('td').siblings('.thisOne').hide();

Also since #datatable is a table, you do not need to specify tr td.. just go for the checkbox..

var boxes = $("#dataTable :checkbox");

Finally checked is also a property of the checkbox, so no need to query for it through jQuery.. You can use element.checked.

Altogether

var boxes = $("#dataTable :checkbox");
var locations = [];
boxes.each(function () {
        if ( this.checked ) {
            //Code here
            $(this).closest('td').siblings('.thisOne').hide();
        }
    });
like image 189
Gabriele Petrioli Avatar answered Dec 22 '25 19:12

Gabriele Petrioli


var boxes = $("#DataTable :checkbox");
$.each(boxes, function() {
    if ( $(this).is(':checked') ) {             
        $(this).closest('td').siblings('.thisOne').hide();
    }
});
like image 23
Ronny Susetyo Avatar answered Dec 22 '25 19:12

Ronny Susetyo