AndreFontaine
AndreFontaine

Reputation: 2584

How to get a particular sibling value

I'm trying to get the value of the sibling with the class i_search when clicked.

<tr>                        
    <td>12</td>
    <td class="request">24</td>
    <td>36</td> 
    <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
</tr>
<tr>                        
    <td>6</td>
    <td class="request">12</td>
    <td>18</td> 
    <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
</tr>
<tr>                        
    <td>3</td>
    <td class="request">6</td>
    <td>9</td>  
    <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
</tr>

here my jQuery:

$(".i_search").on("click", function(event){
    event.preventDefault();
    var numRos = $(this).find(".request:first").val();
});

console.log(numRos);

But it shows null

Upvotes: 0

Views: 2196

Answers (3)

David Thomas
David Thomas

Reputation: 253318

You have two options, the first:

var numRos = $(this).closest('tr').find('.request').text();

Or:

var numRos = $(this).parent().siblings('.request').text();

val() is applicable only to interactive form elements, what you want is the text of a <td>, so text() should be used instead.

Getters, in jQuery, will return, in this case the text, of only the first element matched by the selector. In your case there is only the one, so it will work appropriately.

References:

Upvotes: 1

Irvin Dominin
Irvin Dominin

Reputation: 30993

jQuery find search a child of the element matching the selector, you have to traverse up the DOM and match its parent using closest then you can use find.

Try:

$(".i_search").on("click", function(event){
    event.preventDefault();
    var numRos = $(this).closest("tr").find(".request").text();
    console.log(numRos);
});

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72857

This is what you need:

$(".i_search").on("click", function(event){
    event.preventDefault();
    var numRos = $(this).parents('tr').find('.request').html();
    alert(numRos);
});
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>						
        <td>12</td>
        <td class="request">24</td>
        <td>36</td>	
        <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
    </tr>
    <tr>						
        <td>6</td>
        <td class="request">12</td>
        <td>18</td>	
        <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
    </tr>
    <tr>						
        <td>3</td>
        <td class="request">6</td>
        <td>9</td>	
        <td><a class="i_search" href="javascript:;" title="Detalle">btn</a></td>
    </tr>
</table>

Upvotes: 1

Related Questions