Deviland
Deviland

Reputation: 3374

jquery on click sibling selection

I generate a Table from a database to look like this

<table id="items">
<thead>
    <tr>
        <th>Details</th>
        <th>Goldmine ID</th>
        <th>&nbsp;</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="evenrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="evenrow"><input type="text" value="" id="106" class="gminput"></td>
        <td class="butCell evenrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
    <tr>
        <td class="oddrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="oddrow"><input type="text" value="" id="107" class="gminput"></td>
        <td class="butCell oddrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
    <tr>
        <td class="evenrow">This is a test Description generated through UNIT Tests for the category description</td>
        <td class="evenrow"><input type="text" value="" id="108" class="gminput"></td>
        <td class="butCell oddrow"><button class="saveButton updateitem">Update</button></td>
    </tr>
</tbody>
</table>

I am trying to get the input box value and id returned by the relevant row's button click

so far I have tried this but failed

$('body').on('click', '.updateitem', function(event) {
    event.preventDefault();
    $(this).parent().siblings().each(function(index) {
        alert(($(this).val()));
    });
    var par = sib.parent('td');
    par.addClass('redBorder');
});

Upvotes: 1

Views: 168

Answers (3)

Abhilash
Abhilash

Reputation: 1610

$('.updateitem').on('click', function(){
    $elem = $(this).parents('tr').find('.gminput');
    var id = $elem.prop('id');
    var val = $elem.val()
})

Why have a click event on body, when button might suffice?

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

There is no method forEach() in jQuery.. try .each()

$(this).parent().parent().each(function(index) {
   if(!$(this).hasClass('butCell')) {
       if($(this).find('input').length > 0) { // we have to verify if tds has text inputs or not
           alert($(this).find('input').val());
       } else {
           // if there is no text input we get the text inside td
           alert($(this).text());
       }
   }  
});

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

The element you want is

$(this).closest('tr').find('.gminput')

You can get the value and id using

var input = $(this).closest('tr').find('.gminput');
var value = input.val();
var id = input.attr('id');

Upvotes: 4

Related Questions