2017-06-02 8 views
0

ユーザーが項目と数量を入力できる食料品リストを作成しようとしています。リスト(コード内)にいくつかの項目を追加しましたが、ユーザーが「追加」ボタンを使用して項目を追加できるようにします。ユーザーがobservabaleArraysにデータを入力する方法

ユーザーが「追加」をクリックすると、「新しい4」が追加されます。このデータをユーザー入力します。私はどのようにobservabaleArraysにユーザー入力データを入力させるか分からない。

私はKnockout.jsをかなり新しくしており、これを回避する方法は見つけられません。

<table> 
    <thead> 
     <tr> Item </tr> 
     <tr> Quantity </tr> 
    </thead> 
    <tbody data-bind="foreach: items"> 
     <tr> 
      <td data-bind="text:item"></td> 
      <td data-bind="text:quantity"></td> 
     </tr> 
    </tbody> 
</table> 

<button data-bind="click: addItem"> ADD </button> 

<script> 

    function appViewModel(){ 
      var self = this; 


     self.items = ko.observableArray([ 
      { 
       item: 'Carrot', 
       quantity : '1' 
      }, 
      { 
       item: 'Milk', 
       quantity : '2' 
      }, 
      { 
       item: 'Bread', 
       quantity : '3' 
      } 
     ]); 

     self.addItem = function(){ 
      self.items.push({item: 'New', quantity: '4'}); 
     } 
    } 

    ko.applyBindings(new appViewModel()); 
</script> 

</body> 
</html> 

答えて

0

function item(item, quantity) { 
 
    var self = this; 
 
    this.item = ko.observable(item); 
 
    this.quantity = ko.observable(quantity) 
 
    
 
} 
 

 
function viewModel() { 
 
    var self = this; 
 
    this.item = ko.observable(''); 
 
    this.quantity = ko.observable(''); 
 
    this.items = ko.observableArray([ 
 
    new item('carrot', 1), 
 
    new item('milk', 2), 
 
    new item('bread', 3), 
 
    ]); 
 
    this.add = function(){ 
 
    self.items.push(new item(self.item(), self.quantity())) 
 
    } 
 
} 
 

 
var vm = new viewModel(); 
 
$(document).ready(function() { 
 
    ko.applyBindings(vm); 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <thead> 
 
    <tr> Item </tr> 
 
    <tr> Quantity </tr> 
 
    </thead> 
 
    <tbody data-bind="foreach: items"> 
 
    <tr> 
 
     <td data-bind="text:item"></td> 
 
     <td data-bind="text:quantity"></td> 
 
    </tr> 
 
    </tbody> 
 
</table> 
 

 
<p> 
 
item: <input data-bind="value: item"> 
 
</p> 
 

 
<p> 
 
quantity: <input data-bind="value: quantity"> 
 
</p> 
 
<button data-bind="click: add"> 
 
add 
 
</button>

関連する問題