Question

I am new to knockout and I am trying to add text box values to an observable array of 'item' type. The array is defined in the model. I am not able to print the values from the textbox. The values being printed are undefined. I am not able to make the textbox values populate the 'item' object.

jsFiddle

http://jsfiddle.net/GSvnh/2817/

The following is my code snippet:

HTML
----
<body>
<div > 
    <ul data-bind="foreach: { data: itemArray}">
    <li data-bind="text: $data.fullName"></li>
</ul>

<input data-bind="value:newItem.firstName" placeholder="FN"></input>
<input data-bind="value:newItem.lastName" placeholder="LN"></input>    
<button data-bind="click: addItem">Add</button>

</div>
</body>

SCRIPT
------

<script>


function item()
{
    var self = this;
    self.firstName = ko.observable();
    self.lastName = ko.observable();
    self.fullName = ko.computed(function() {
        return self.firstName() + "-" + self.lastName();
    });

}
function model(){
    var self1 = this;
    self1.itemArray = ko.observableArray();
    self1.newItem = ko.observable(new item());
    self1.addItem = function(){
      self1.itemArray.push(self1.newItem);
    };

};
var mod = new model();
ko.applyBindings(mod);

</script>
Was it helpful?

Solution

http://jsfiddle.net/GSvnh/2828/

You need to add parans behind newItem

<input data-bind="value:newItem().firstName" placeholder="FN"></input>
<input data-bind="value:newItem().lastName" placeholder="LN"></input>    

I also updated a few other things for you to give you some direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top