tomor
tomor

Reputation: 1765

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>

Upvotes: 8

Views: 7602

Answers (3)

Peter Agar
Peter Agar

Reputation: 76

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;
  }
}

Upvotes: 4

Cyanfish
Cyanfish

Reputation: 4163

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.

Upvotes: 10

Nick
Nick

Reputation: 4212

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';
    }

Upvotes: 3

Related Questions