knockout.js Bindings - Form fields Value


Use the value binding to obtain the value of an element. The value binding can be applied to any form control, however there are other bindings that may be better suited for checkboxes, radio buttons, and text inputs.

The following example illustrates how to apply the binding element to several form input fields, and how to populate default values:

ViewModel definition:

var MyViewModel = function(){
    var self = this;
  //Initialize valueOne
  self.valueOne = ko.observable();
  //Initialize valueTwo with a default value of "Value two"
  self.valueTwo = ko.observable("Value two");
  //Initialize the color dropdown, and by default, select the "blue" option
  self.color = ko.observable("blue");
      console.log("valueOne: " + newValue);
      console.log("valueTwo: " + newValue);
      console.log("color: " + newValue);

Associated markup:

<input type="text" data-bind="value: valueOne" />
<input type="text" data-bind="value: valueTwo" />

<select data-bind="value: color">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>

In the above example, when a value changes, the new value will be logged to the console. The initial values will not trigger a change event.

By default, the value binding defines a change as a change to the elements value, and focus being transferred to another element. This can be altered using the valueUpdate option:

<input type="text" data-bind="value: valueOne, valueUpdate: 'keyup'" />

The above example will change the value update to trigger on key up. Available options are input, keyup, keypress, and afterkeydown.