1

I want to print the value of an input element in console using knockout.

When I try to print that value I am getting "result" instead of the value of the textbox.

var ViewModel = {
   name: ko.observable("name"),
   company: ko.observable("company"),
   submit: ko.observable("Submit"),
   onsubmit: function(){
      console.log(name);
   }
}

ko.applyBindings(ViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<form>
   <label>Name</label>
   <input type="text" data-bind="value:name"/>
   <label>Company</label>
   <input type="text" data-bind="value:company"/>
   <button data-bind="click:onsubmit,text:submit"></button>
</form>
Tomalak
  • 306,836
  • 62
  • 485
  • 598

1 Answers1

1

You can also do it this way. I like to declare a function for my viewmodel so that later it can be used to initialize another new object.

var ViewModel = function() {
  var self = this;
  self.name = ko.observable("name");
  self.company = ko.observable("company");
  self.submit = ko.observable("Submit");
  self.onsubmit = function(){
   alert(self.name())
   console.log(self.name());
  };
}
ko.applyBindings(new ViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>Name</label>
<input type="text" data-bind="value: name"/>
<label>Company</label>
<input type="text" data-bind="value: company"/>
<button data-bind="click: onsubmit, text: submit"></button>
muhihsan
  • 1,958
  • 6
  • 19
  • 37
  • Thanks it worked. Can you please explain me what I was doing wrong –  Apr 02 '17 at 04:39
  • I believe the problem is because when you call console.log(name), name there doesn't refer to the same name observable value that you've declared. And this can be fixed by doing var self = this; and you use self.name to make sure it refers to the right name object – muhihsan Apr 02 '17 at 04:42
  • can we directly use "this.name " instead? –  Apr 02 '17 at 04:44
  • and also you have changed name into function(). What significance does that hold? –  Apr 02 '17 at 04:46
  • That's how you read a value of an observable object. http://knockoutjs.com/documentation/observables.html – muhihsan Apr 02 '17 at 04:49
  • Thanks. Great Help –  Apr 02 '17 at 04:49
  • 1
    @M.Ihsan In fact it would have been enough change `console.log(name);` to `console.log(this.name())`. In knockout event handlers, `this` will be a reference to the viewmodel. – Tomalak Apr 03 '17 at 08:59
  • Thanks for clarifying. Yup, that's correct. I was a bit mixed up before. I just like to do `var self = this` so that I don't even need to think about this scenario http://stackoverflow.com/questions/17163248/whats-the-advantage-of-using-var-self-this-in-knockout-js-view-models. – muhihsan Apr 03 '17 at 09:58