1

I have a datatable. I want to simply add a row or delete dynamically. For deleting the row we simply use fnRowDelete() function which makes all task easy.

<table>
  <tr>
    <td><p>sr no</p></td>
    <td><div>First name</div></td>
    <td><div>Last name</div></td>
  </tr>
</table>

However adding a new row using fnAddData(1,"john","doe") does the job but it will add a row by adding this data directly inside the tag with no custom html.

<table>
  <tr>
    <td>1</td>
    <td>john</td>
    <td>doe</td>
  </tr>
</table>

Here i want to add this row with its html tags as well. if we pass html as string in the function fnAddData() to get required output, we will not be able to make both javascript and html code separate (use of template).

Is there any way how i can keep both javascript and html code in different file and still be able to add a row in required format.

Required sample output:-

<table>
  <tr>
    <td><p>1</p></td>
    <td><div>john</div></td>
    <td><div>doe</div></td>
  </tr>
</table>
miken32
  • 42,008
  • 16
  • 111
  • 154
  • there should be a way like "append" does to add data in an element. Look at jQuery doc... btw, look at this : http://stackoverflow.com/questions/171027/add-table-row-in-jquery . This does the job, and you can put whatever you want in your table... – Julo0sS Apr 16 '15 at 06:59
  • @jayshree - show your function fnAddData() – Shivang MIttal Apr 16 '15 at 07:00
  • If you want to get your html data from a seperated file, just use jQuery $.ajax({}) function and callback the result. Then, to add your row, just check my previous comment... or use your mysterious fnAddData function! – Julo0sS Apr 16 '15 at 07:05
  • @Julo0sS adding a row using dom manipulation functions like append helps in ui visibility but since it is not in datatable, functionality like search and sort of datatable will not consider the html row we have added. – Jayshree Chaudhary Apr 16 '15 at 09:25
  • @Shiv fnAddData() is the function of dataTable itself. http://datatables.net/forums/discussion/19004/fnadddata-add-multiple-rows-at-once-show-hide-table – Jayshree Chaudhary Apr 16 '15 at 09:26
  • @JayshreeChaudhary : to add into database and do manipulations on it, you just have to use .ajax + php + your db! then, to display, use jquery append.. where is the problem? – Julo0sS Apr 17 '15 at 06:57

2 Answers2

1

The better way to do is add custom template to your data-table rows.

 "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]

When Data is null, it will take from default template. If you want, you can format the data with the template according to your requirement.

Aarthi Chandrasekaran
  • 569
  • 2
  • 10
  • 21
-2

use .html() to append. like this

$( "td" ).html( "<p>+'jsonData.Number'+</p>" );
Arun
  • 142
  • 1
  • 1
  • 9