See the code in files and try like this.
grid.phtml
<div id="block-sample-grid" data-bind="scope:'sample-grid'" class="block">
<!-- ko template: getTemplate() --><!-- /ko -->
<script type="text/x-magento-init">
{
"#block-sample-grid": {
"Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
}
}
</script>
</div>
grid.html
<h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</h2>
<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name" /></td>
<td><select data-bind="options: $parent.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="text: formattedPrice"></td>
<td><a href="#" data-bind="click: function(data,event){$parent.removeSeat($parent,data);}">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click:addSeat, enable: seats().length < 5 ">Reserve another seat</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
grid.js
define(
[
'jquery',
'ko',
'uiComponent',
],
function ($, ko, component) {
"use strict";
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
self.formattedPrice = ko.computed(function() {
var price = self.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
}
return component.extend({
seats: ko.observableArray([]),
availableMeals : ko.observableArray([]),
addSeat : function() {
var seat = new SeatReservation ("Your Name",this.availableMeals()[0]);
this.seats.push(seat);
},
removeSeat : function(parent,seat) {
parent.seats.remove(seat);
},
addMeal:function(meals){
for (var i in meals){
this.availableMeals.push(meals[i]);
}
},
totalSurcharge : function() {
var total = 0;
for (var i = 0; i < this.seats().length; i++)
total += this.seats()[i].meal().price;
return total;
},
initialize: function () {
this._super();
this._render();
this.totalfeeds();
},
_render:function(){
var self = this;
var meals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
this.addMeal(meals);
var init_seats = [
new SeatReservation ("Henry",this.availableMeals()[0]),
new SeatReservation ("Bert",this.availableMeals()[0]),
];
for(var i in init_seats){
this.seats.push(init_seats[i]);
}
},
defaults: {
template: 'Thienphucvx_Knockout/grid',
},
});
}
);