2

I have this table, and I want to add Rows up the button, in the same rowId. For example, on clicking the Add Row 1 button, i want to add a row in row1, under "Some content 1", and so on.

  <table id="table1">
       <thead>
         <th>Heading 1</th>
         <th>Heading 2</th>
       </thead>
       <tbody>
         <tr id="row1">
            <td>Some content 1<td>
            <td><button id="addButton1">Add Row 1</button><td>
         </tr>
         <tr id="row2">
            <td>Some content 2<td>
            <td><button id="addButton2">Add Row 2</button><td>
         </tr>
       <tbody>
    </table>

This is the script I use so far:

$("#addBtn").on("click", function () {
    $("#table1 tbody").append("<tr><td>1</td><td>1</td></tr>");

});

This is adding rows at the end of the table. How can I add rows in between, in the same section, using jQuery?

2 Answers 2

2

Try to use .closest() along with .after() to achieve what you want, and you should use id starts with selector in this context or you can add one common class for all of that buttons and use that as a selector.

$("[id^=addButton]").on("click", function () {
    $(this).closest('tr').after("<tr><td>1</td><td>1</td></tr>");
});

Side Note: I have edited some of your ugly html in order to make your code valid

DEMO

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

Comments

1

You can do like this.

$("#table1 button").on("click", function () {    
$(this).parents('tr').after("<tr><td>1</td><td>1</td></tr>");
});

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.