Enot
Enot

Reputation: 830

Select an element with a specified class with parent in JQuery

I don't know what's wrong, i have as follows:

<tr>
  <td><span class="idTask">1</span></td>               
  <td><span>Another Hello</span></td>                              
  <td><img class="delete" src="img/delete.png" alt="Edit" /></td>
  <td><input type="checkbox" name="delete[]" value="" /></td>
</tr>

When i click a button a function calls to iterate through the all checked box for being delete, i need to retrieve the value from idTask, i'm trying to do as follows:

$(function(){
    $(".deleteAll").click( function(){
    var conf=confirm("Are you sure?");
    if(conf==true) {  
        $(':checkbox').each(function () {
        if(this.checked) {
            alert(($(this)).parent().find('.idTask').text());
        } 
        });
    }
    });
});

But doesn't work, with prev() or next() works, but is not for me an elegant way to do this, any suggestions for find a children element matching his class inside a parent to retrieve his value?

Upvotes: 0

Views: 168

Answers (1)

VisioN
VisioN

Reputation: 145458

The parent of the checkbox is <td> but not <tr>. You should better use closest():

$(".deleteAll").click(function() {
    if (confirm("Are you sure?")) {
        $(":checkbox").each(function() {
            if (this.checked) {
                // --------------.-.-.-.-.-.-.
                //               v v v v v v v
                var id = $(this).closest("tr").find(".idTask").text();
                alert(id);
            }
        });
    }
});

Upvotes: 1

Related Questions