0

I'm using the following:

HTML

 <table id="tracks" class="BorderedTable"   
   <tr>
    <td  style="text-align:center; background-color:#00FFFF"> 
        TITLE
    </td>
 </tr>

 <!-- This is part of a much larger loop that adds several rows -->
   <tr class="border_bottom">
     <td>
      <!-- I want to add a column after whichever of this row was clicked on -->
      <a onclick="addTableRow($('#tracks'));" > +/- </a>
    </td>
   </tr>
 </table>

JQUERY

function addTableRow(jQtable){
    jQtable.each(function(){
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for(var i = 0; i < n; i++){
            tds += '<td>&nbsp;</td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        }else {
            $(this).append(tds);
        }
    });
}

This adds a row at the end of the table. How can I make it add a row after another specific row?

3
  • 1
    Please post a complete code example. Commented Jan 15, 2015 at 14:42
  • 1
    Add relevant codes to the snippet to demonstrate how what you have works. Both HTML, the Script and CSS if possible. Commented Jan 15, 2015 at 14:42
  • just thinking initially, but you could start with the idea of passing in the index of the row you want to insert after. Commented Jan 15, 2015 at 14:45

1 Answer 1

1

To append an element right after a specific element you can use after() function:

EDIT: Clicking on a row, a new row is appended after it

$(document).on('click', '#add', function() {
  $('#test').after('<tr><td>row added</td></tr>');
});

$(document).on('click', 'tr', function() {
    var that = $(this);
    that.after('<tr><td>appended after clicked tr</td></tr>');
});
  
table { 
  width:100%;
  border-collapse: collapse;
}
td {
  border: 1px solid #333;
}
#add {
  display: inline-block;
  padding: 10px;
  background-color: #555;
  color: #fff;
  margin-top: 30px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr id="test">
      <td>test1</td>
    </tr>
    <tr>
      <td>test2</td>
    </tr>
    <tr>
      <td>test2</td>
    </tr>
    <tr>
      <td>test2</td>
    </tr>
  </tbody>
</table>

<span id="add">add row after first row</span>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.