jack rose
jack rose

Reputation: 97

How to select just previous row of the last row

How to select just previous row of the last row?

My html code:

<table id="table1">
 <tr><td>test</td></tr>
 <tr><td>test</td></tr>
 <tr><td>test</td></tr>
 <tr><td><select></select></td></tr>
 <tr><td>test</td></tr>
</table>

Now I want to give option to the using jquery.

js:

$('#table1 tr:last select').prev().append("<option>rose</option>");

But it doesn't worked. Please help.

fiddle: http://jsfiddle.net/xzj5m3w8/

Upvotes: 0

Views: 217

Answers (3)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this :

$('#table1 tr:nth-last-child(2)').find('select').append("<option>rose</option>");

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

tr:last select will look for select in last row. you need to find the last row first, traverse to previous tr and then find select element in it. Like this:

$('#table1 tr:last').prev().find('select').append("<option>rose</option>");

Working Demo

From the markup it appears that you have only single select. if that is the case always, you need not have to do all the traversing and stuff. $('#table1 select') will work for targeting single select element.

Upvotes: 3

kapantzak
kapantzak

Reputation: 11750

In the specific table there is only one select element, so you can just use find() in the parent table:

$('#table1').find('select').append('<option>rose</option>');

Another approach would be this:

$('#table1 tr').each(function() {
   var that = $(this);
   var l = that.find('select').length;
   if (l > 0) {
      // the row has a select element ...
   }
});

Upvotes: 2

Related Questions