jqueryfindappendinsertafter

Jquery: Insert a new row after a row that contain specific column value


how can I append a new row after a row which has a specific column value using Jquery?

For example, I wish to append a new row of column [NAME: CINDY AGE: 21] after 'Selina' because I wish to append a new row which is sorted by 'AGE' and [NAME: Tori AGE: 26] will be appended after 'Kelly'.

<table>
  <tr>
    <th>NAME</th>
    <th>AGE</th>
  </tr>
  <tbody>
    <tr>
      <td>Alice</td>
      <td>18</td>
    </tr>
    <tr>
      <td>Selina</td>
      <td>20</td>
    </tr>
    <tr>    
      <td>Kelly</td>
      <td>25</td>
    </tr>
  </tbody>
</table>
<input type="text" name="name" id="name" placeholder="NAME">
<input type="text" name="age" id="age" placeholder="AGE">
<button type="button" id="add_btn">ADD</button>

Thank you. Cheer :)


Solution

  • This should work:

    jQuery('#add_btn').on('click',function(){
      var age = jQuery('#age').val();
      var name = jQuery('#name').val();
        var target = jQuery('tbody > tr > td:last-child').filter(function(){
        return jQuery(this).text() >= age;
      }).first().parent();
      if(target.length > 0)
        target.before('<tr><td>'+name+'</td><td>'+age+'</td></tr>');
      else
        jQuery('tbody > tr:last').after('<tr><td>'+name+'</td><td>'+age+'</td></tr>');
    });
    

    jsFiddle