How to get the value of a textbox onchange with knockout.js?

Member

by mac , in category: Javascript , 7 months ago

How to get the value of a textbox onchange with knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 7 months ago

@mac 

You can use the valueUpdate binding in knockout.js to achieve this. The valueUpdate binding allows you to specify when the observable associated with the text input should be updated. By setting the valueUpdate binding to 'input', the observable will be updated whenever the user types in the textbox.


Here is an example of how you can get the value of a textbox onChange using knockout.js:


HTML:

1
2
<input type="text" data-bind="value: inputValue, valueUpdate: 'input', event: { change: getInputValue }">
<p>The value of the textbox is: <span data-bind="text: inputValue"></span></p>


JavaScript:

1
2
3
4
5
6
7
8
9
function ViewModel() {
    this.inputValue = ko.observable('');

    this.getInputValue = function() {
        console.log(this.inputValue());
    }
}

ko.applyBindings(new ViewModel());


In this example, whenever the user changes the value of the textbox, the getInputValue function will be called and the value of the textbox will be logged to the console. The value of the textbox is also displayed below the textbox using knockout.js data binding.

Related Threads:

How to set a textbox value in ember.js?
How to get value of model when iterating over collection in knockout.js?
How to get value from another model in codeigniter?
How to get a scalar value from mysql in node.js?
How to change value of an array in knockout.js?
How to assign undefined value in a knockout.js variable?