Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update the observable when input value is changed by Javascript

Is there a way to update an observable when the <input> value is changed, but programatically, i.e. by Javascript?

Here is a jsfiddle of this use case that I am not able to make it work: http://jsfiddle.net/qYXdJ/

As you see when the "Update input value by Javascript" link is clicked the observable is obviously not updated, since it is not reflected in the <span>

like image 504
tomor Avatar asked May 01 '13 18:05

tomor


3 Answers

If you absolutely can't modify the observable directly (which is the best way), you can trigger the "onchange" event (which Knockout uses internally). With jQuery, it's a simple matter:

$('#update').on('click', function() {
    $('#input2').val('New Value').trigger('change');
});

If you don't want to use jQuery for whatever reason, have a look at this question.

like image 97
Cyanfish Avatar answered Nov 12 '22 03:11

Cyanfish


As cyanfish pointed out the correct way is to update the observable.

If the problem is your code doesn't have access to the observable, for example you're writing a bookmarklet to automatically fill out a form, then you can gain access to the observable like this:

function setValue(input, value) {
  var bindingsString = input.getAttribute('data-bind');
  if (bindingsString) {
    var bindings = ko.bindingProvider.instance.parseBindingsString(bindingsString, ko.contextFor(input), input);
    if (bindings.value) {
      bindings.value(value);
    } else if (bindings.checked) {
      bindings.checked(value);
    } else {
      input.value = value;
    }
  } else {
    input.value = value;
  }
}
like image 31
Peter Agar Avatar answered Nov 12 '22 01:11

Peter Agar


You have to change the viewModel 'name' property instead of input field value, because it's observable, and any changes on the property will be reflected to all binded html elements.

var viewModel = {
        name: ko.observable()
    };
    ko.applyBindings(viewModel);

    document.getElementById('update').onclick = function(){
        viewModel.name('New Value');
        //document.getElementById('input2').value = 'New Value';
    }
like image 32
Nikola Mitev Avatar answered Nov 12 '22 02:11

Nikola Mitev