Knockoutjs Demo

by SpAm

HTML

<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.css">
<div class="container">

<div class="tableRes">
  <table class="table table-bordered">
    <tbody data-bind="foreach: people">
      <tr>
        <td data-bind="text: firstName"></td>
        <td data-bind="text: lastName"></td>
      </tr>
    </tbody>
  </table>
</div>


<div class='panel panel-default'>
  <div class="panel-body">
    <input placeHolder="First Name" data-bind='value: firstName' />
    <input placeHolder="Last Name" data-bind='value: lastName' /> 
  <button type="button" class="btn btn-xs btn-default" data-bind='click: addChild '>Add child</button>
    <div data-bind="visible: displayError" style="margin:10px 0;">
      <div data-bind="text: error" class="alert alert-danger" role="alert">
      </div> 
    </div>
  </div>
</div>

  
    
</div>

JavaScript

var ViewModel = function () {
  this.people = ko.observableArray([]);
  this.firstName = ko.observable();
  this.lastName = ko.observable();

  this.displayError = ko.observable(false);
  this.error = ko.observable();
  
  this.addChild = function () {

    var pep = {
      firstName: this.firstName(),
      lastName: this.lastName()
    };
	
    
    if (!pep.firstName) {
      this.error("Please enter a first name");
      this.displayError(true);
       return;
    } else if (!pep.lastName) {
      this.error("Please enter a last name");
      this.displayError(true);
      return;
    }

    this.people.push(pep);
    this.firstName("");
    this.lastName("");
    
  }.bind(this);
  
};

ko.applyBindings(new ViewModel());