Vasco Vasco - 2 years ago 41
HTML Question

Knockout adding row

I´m new at knockout and I am trying to make a table, when we click "Remover" it removes the line, but when I click "Adicionar" I can't add any row to the table. If someone could help me I appreciate it.

<title> Inseminações </title>
<link rel="stylesheet" type="text/css" href="style.css" />
<div id='cssmenu'>
<li><a href="inseminações.html">Inseminações</a>
<li><a href="tratamentos.html">Tratamentos</a>
<li><a href="analises.html">Análises Clínicas</a>
<h1> Inseminações </h1>
<th>SIA Vaca</th>
<th>SIA Touro</th>
<th>Nome do Touro</th>
<th> </th>
<tbody data-bind="foreach: dtabela">
<td data-bind="text: Data"></td>
<td data-bind="text: SIAV"></td>
<td data-bind="text: SIAT"></td>
<td data-bind="text: NomeT"></td>
<td data-bind="text: Doc"></td>
<td data-bind="text: Ins"></td>
<td><button data-bind='click: $root.removeDados'>Remover</button></td>
<td><input data-bind='value: Data'/></td>
<td><input data-bind='value: SIAV'/></td>
<td><input data-bind='value: SIAT'/></td>
<td><input data-bind='value: NomeT'/></td>
<td><input data-bind='value: Doc'/></td>
<td><input data-bind='value: Ins'/></td>
<td><button data-bind='click: $root.addDados'>Adicionar</button></td>

<script type='text/javascript' src='knockout-3.0.0.js'></script>
<script type='text/javascript'>
function Dados(Data,SIAV,SIAT,NomeT,Doc,Ins) {
this.Data = ko.observable(Data);
this.SIAV = ko.observable(SIAV);
this.SIAT = ko.observable(SIAT);
this.NomeT = ko.observable(NomeT);
this.Doc = ko.observable(Doc);
this.Ins= ko.observable(Ins);
function DadosViewModel ()
var self= this
new Dados("30-01-13", 354, 564, "Touro 1", "Doc1", "Inseminador A"),
new Dados("12-05-13", 785, 344, "Touro 3", "Doc5", "Inseminador B"),
this.removeDados=function(Dados) {
this.addDados=function(Dados) {
self.dtabela.push( new Dados);
var vm= new DadosViewModel();

Answer Source

Ok, I got your sample working, you can see a demo here:

I had to make the following amendments

  1. You had no viewmodel property to represent the new item, I added one:

    function DadosViewModel () 
        var self= this
        this.newDados = ko.observable( new Dados(); ) // Here
  2. You had 2 tbody tags, I change one to a tfoot and used the with binding to bind the footer row to the newDados viewmodel property

    <tfoot data-bind="with: newDados">
  3. When passing this instance to the addDados method, I recreated newDados

    function DadosViewModel ()
          this.addDados=function(d) {                
            self.dtabela.push( d );
            self.newDados( new Dados() );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download