2

I am trying to insert a row dynamically in my table, but I have no luck to achieve this.

In my ajax success this is how I insert the table row

$('#mytable').find('tbody').append(data); 

HTML:

<table  class="display" id="mytable" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>#</th>
      <th>FIRST NAME</th>
      <th>LAST NAME</th>
      <th>ADDRESS</th>
      <th>AGE</th>
    </tr>
  </thead>
  <tbody>
    // I want to insert here.
  </tbody>
</table>

This is the data that is being returned.

<tr class="myclass">
  <td style="text-align: center;">1</td>
  <td>Jack</td>
  <td>Miller</td>
  <td>California</td>
  <td>24</td>    
</tr>
<tr class="myclass">
  <td style="text-align: center;">2</td>
  <td>Miguel</td>
  <td>Park</td>
  <td>London</td>
  <td>64</td>     
</tr>

Thank you in advance.

5
  • @ashTon what does your API return? The data that you are appending should either be a html string or an element ( can also be collection of either) Commented Oct 30, 2014 at 3:15
  • 1
    //loop{ $.each loop $('#mytable').find('tbody').append("<tr><td>"+"data"+"</td></tr>"); //} Commented Oct 30, 2014 at 3:27
  • You need to open your console, preferably in FF or chrome (hit f12) and check the status of your ajax call. I think your issue lies with that. As it stands your code works with a string: jsfiddle.net/ektnku0h Commented Oct 30, 2014 at 3:33
  • Than you I fixed it now Commented Oct 30, 2014 at 3:35
  • @surajrawat post it as Answer. Commented Oct 30, 2014 at 4:44

2 Answers 2

1

use a each loop and append the data with HTML via append method

  $.each(data,function(value,index){}{

     $('#mytable').find('tbody').append("<tr><td>"+value+"</td></tr>"); 

  });{
Sign up to request clarification or add additional context in comments.

Comments

0

It will add the row dynamically..

<!DOCTYPE html>
    <html>
    <head>
    <style>
    table, td {
        border: 1px solid black;
    }
    </style>
    </head>
    <body> 
<table id="myTable">
  <tr>
    <td>Row1 cell1</td>
    <td>Row1 cell2</td>
  </tr>
  <tr>
    <td>Row2 cell1</td>
    <td>Row2 cell2</td>
  </tr>
  <tr>
    <td>Row3 cell1</td>
    <td>Row3 cell2</td>
  </tr>
</table>
<br>

<button onclick="myFunction()">Add row</button>

<script>
function myFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}
</script>

</body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.