JSFiddle - React, Tailwind, and code Playground

by Norlihazmey Ghazali

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<table id="myTable" border=1>
	<thead>
		<tr>
			<td>Name <button id="addBtn">Add Row</button></td>
		</tr>
	</thead>
	<tbody></tbody>
</table>

<script id="row-template" type="text/x-handlebars-template">
    <tr>
		   <td>
			 		<select>
						  {{#each data}}
								<option>{{first_name}}</option>
						  {{/each}}		
					</select>			
			</td>
		</tr>	
</script>

JavaScript

var globalData = '';
var source   = document.getElementById("row-template").innerHTML;
var template = Handlebars.compile(source);

$('#addBtn').click(function() {
	getData(function (data) {
	   
	   var html = template(data);
		 
		 if ($('#myTable').find('tbody tr').length) {
		    $('#myTable').find('tbody').append(html)
		 }
		 else {
		    $('#myTable').find('tbody').html(html)
		 }
	})
});

function getData(callback) {
   // subsequence call hnya panggil dari global variable, boleh speed up performance
   if (globalData) {
	   return callback(globalData);
	 }
	 // panggil php backend, lepas tu hntr data dlm bentuk json
   $.ajax({
		method: 'get',
		url: 'https://reqres.in/api/users',
		success: function (data) {
		   // cache data
		   globalData = data;
		   callback(data)
		}
	})
}