I've recently started to learn knockoutjs ( i think its brilliant. ) However messing around with it and learning how to add to an array i've gotten stuck and need a little help. Fiddle can be found here
Here is my html code:
<h3>We need more animals</h3>
<form data-bind="submit: addAnimal">
<input type="text" data-bind="value: animalToAdd, valueUpdate: 'afterkeydown'"/>
<button type="submit">Add animal</button>
</form>
<select data-bind="options: animalArray, optionsText: 'name'"></select>
<p data-bind="text: selectedAnimal"></p>
And here is my knockoutjs code:
function viewModel(){
var self = this;
self.animalArray = ko.observableArray([
{
name: 'elephant'
},
{
name: 'dog'
},
{
name: 'cat'
}
]);
self.animalToAdd = ko.observable();
self.addAnimal = function(){
if(self.animalToAdd() != ''){
self.animalArray.push(self.animalToAdd());
self.animalToAdd('');
}
alert(self.animalToAdd());
}
}
ko.applyBindings(viewModel);
For some reason i can't get the new animal to push into the current array of animals - I aren't 100% what im doing wrong, as it puts the value in, but not the text.
Any help would be great :)