1

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 :)

1 Answer 1

1
  • First mistake, you are missing definition for selectedAnimal but since you are using it in text binding, your code is breaking
  • Second mistake, animal has a structure { name: 'elephant' } but you are pushing like self.animalArray.push(self.animalToAdd()), so even if you push, you will not see anything in select.

Updated JSFiddle

Pointers

  • Knockout added new binding for value: animalToAdd, valueUpdate: 'afterkeydown' called textInput. This was introduced in KO 3.2 so if you are using above that version, use it.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the info :) helped me out lots.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.