Update observable when input value changes to Javascript

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

Here is the jsfiddle of this use case, which I cannot get it to work: http://jsfiddle.net/qYXdJ/

As you can 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>

+7
source share
3 answers

If you absolutely cannot change the observable directly (which is the best way), you can trigger the "onchange" event (which uses the knockout inside). With jQuery, this is simple:

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

If you don't want to use jQuery for any reason, check out this question .

+9
source

You must change the viewModel 'name' property instead of the value of the input field, since it is observable, and any changes to the property will be displayed in all the associated 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'; } 
+3
source

As cyanfic has shown, the correct way is updating the observable.

If the problem is that your code does not have access to the observable, for example, you write a bookmarklet to automatically fill out the form, then you can access the observable as follows:

 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; } } 
+3
source

All Articles