I am trying to create a table of employees using knockout.js. I have an array that is looped over for a table, and I have functions to edit and delete, but I want to create a text input box for adding Employees to the array, and in turn updating the table with the new employee's information. I have tried everything I know how to do, but since I am a beginner in knockout and javascript for that matter, I don't really know how to accomplish this.
HTML:
<div class="form-group row">
<label for="txtEmployee" class="col-2 col-form-label">Name: </label>
<div class="col-6">
<input type="text"
data-bind="value: nameToAdd, valueUpdate: 'afterkeydown'"
class="form-control"
id="txtName" />
</div>
<div class="col-4">
<a href="#" data-bind="click: $root.add" class="btn btn-primary">Add</a>
</div>
</div>
<table class="table table-dark table-striped table-hover">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Functions</th>
</tr>
</thead>
<tbody data-bind="foreach: Employees">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td>
<span>
<a href="#" class="btn btn-success" data-bind="click: $root.edit">
<i class="fa fa-pencil fa-lg"> </i> EDIT
</a>
</span>
|
<span>
<a href="#" class="btn btn-danger" data-bind="click: $root.remove">
<i class="fa fa-trash-o fa-lg"> </i> DELETE
</a>
</span>
</td>
</tr>
</tbody>
</table>
Javascript:
function Employee(id, name) {
this.Id = id;
this.Name = name;
};
var employeeList = [
new Employee(1, "Justin"),
new Employee(2, "John"),
new Employee(3, "Sarah"),
new Employee(4, "Tyler"),
new Employee(5, "Mason")
];
function PayrollViewModel() {
var self = this;
self.nameToAdd = ko.observable("");
self.Id = ko.observable("");
self.Name = ko.observable("");
var Employee = {
Id: self.Id,
Name: self.Name
};
self.Employee = ko.observable();
self.Employees = ko.observableArray(employeeList);
self.edit = function(Employee) {
self.Employee(Employee);
};
self.remove = function(Employee) {
self.Employees.remove(Employee);
};
self.cancel = function() {
self.Employee(null);
};
self.update = function() {
var l_employee = self.Employee();
self.Employees.remove(self.Employee());
self.Employees.push(l_employee);
};
self.add = function() {
var random = Math.floor((Math.random() * 100) + 1);
this.Employees = [
new Employee(random, nameToAdd)
]
this.nameToAdd("");
};
};
ko.applyBindings(new PayrollViewModel());