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>
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.
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;
}
}
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With