Matt M.
Matt M.

Reputation: 822

Knockout.js force change after JavaScript changes a textbox

I have an input:

<input id="MyTextBox" type="text" data-bind="value: MyTextBox" />

If I change the textbox myself then data binding works... but if I set the text of the textbox with JQuery the textbox changes but no data bind occurs.

$("#MyTextBox").val("Some text");

How can I change a textbox without any keystrokes and still get binding to work?

Thank you

Upvotes: 0

Views: 1008

Answers (2)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

When the change event was triggered will notify observer see the snippet, but i suggest to you use a custom bind handler to manipulate the directly DOM with KO;

You’re not limited to using the built-in bindings like click, value, and so on — you can create your own ones. This is how to control how observables interact with DOM elements, and gives you a lot of flexibility to encapsulate sophisticated behaviors in an easy-to-reuse way.

Ref. http://knockoutjs.com/documentation/custom-bindings.html

function viewModel(){
     this.val = ko.observable()
};

viewModel.prototype.changeValue= function(){
       $("#txt_data").val("Updated by JQuery: " + $("#txt_jqr").val()).change();      
};

ko.applyBindings(new viewModel());
label{
  margin-top:10px;
   display:block;
}
span{
    font-size: 1.4rem;
    font-weight: 700;
    margin-left: 20px;
    color: white;
    background-color: red;
    padding: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label for="txt_data">Data-Bind Text:</label>
<input type="text" id="txt_data" data-bind="value: val"/>
<span data-bind="text: val"></span>
<br/>
<label for="txt_jqr">Jquery Text to change:</label>
<input type="text" id="txt_jqr"/>
<br/>
<br/>
<button data-bind="click: changeValue">Change view model value</button>

Upvotes: 1

Michael Best
Michael Best

Reputation: 16688

When using Knockout, you generally shouldn't be using something else to modify the view. So instead of using jQuery to change the textbox value, use Knockout by modifying the observable it's bound to:

this.MyTextBox("Some text");

If you really need to modify the textbox outside of Knockout, you can signal the value binding by generating a change event:

$("#MyTextBox").val("Some text").change();

Upvotes: 4

Related Questions