Jumat, 04 Februari 2022

Datatable : Adding a Row Dynamically and adding its atrribute

Ok, I had a problem to solve the problem I mentioned in the title of this post. 

So, I combined two solution from two sources (Actually I've browsed to several websites and discussions). 

These are my sources: Source 1, Source 2.

I use ajax to retrieve the data and then add them dynamically to the table. Then, I want to align the text to center and add onclick event on each row.

So here is my Table:


<div class="table-responsive">
	<table class="table table-striped table-bordered" 
    	id="transaction_detail" cellspacing="0" width="100%">
		<thead>
			<tr class="text-center align-middle">
				<th>Name</th>
				<th>email</th>
				<th>Phone</th>
				<th>Transactions</th>
				<th>Turnover</th>

			</tr>
		</thead>
		<tbody >

				
		</tbody>
	</table>
</div>


And here is my Ajax:


$.ajax({
  type:"POST",
  url:"/gettransaction",
  data:{customer_id: customerid},
  success:function(data){
	var jsondat = JSON.parse(data)  ;
	
	//clear the table's body
	$("#transaction_detail").DataTable().clear().draw();

	if(jsondat.length > 0){
		for(var i=0; i<jsondat.length; i++){
			
			var rowTab = $("#transaction_detail")
				.DataTable()
				.row
				.add([
				jsondat[i].customer_name,
				jsondat[i].customer_address,
				jsondat[i].customer_phone,
				jsondat[i].number_transaction,
				jsondat[i].turnover
			]);


			//use node() so that row is editable.
			var rowEdit = rowTab.node();

			$(rowEdit).attr("style", 
				"cursor:pointer; text-align:center");
			$(rowEdit).attr('onclick',
            	"showTrans("+jsondat[i].customer_id+")");

			//redraw the table after its modified
			rowTab.draw(false);
		}   

	}
  },
  error: function(){

  }
});


I hope it can help you somehow. cheers!!

Tidak ada komentar:

Posting Komentar