Using keypress event in knockout JS
Solution 1
- make sure query is an observable
- use
valueUpdate = 'afterkeydown'
- use
event: { 'keyup': check }:
Also I'd use console.log if possible as opposed to alert, and log the query so you can make sure the value is updating. :) you also my want to log the event like this
function check(data, event) {
console.log(event);
}
that will tell you the keycode for the key you pressed
Solution 2
This thread is old, but I've noticed it doesn't cite use of KO's textInput binding. This is a new feature added in v3.2.0.
The KO docs, at least as of now (Jan-2015), specifically addresses this issue:
Note 1: textInput vs value binding
Although the value binding can also perform two-way binding between text boxes and viewmodel properties, you should prefer textInput whenever you want immediate live updates.
See http://knockoutjs.com/documentation/textinput-binding.html
Comments
-
divyanshm almost 4 years
I'm trying to read the contents of an html textbox and fetch data from an API to accomplish a google style auto complete. I'm using
twitter bootstrap typeahead
for the auto complete functionality. For that I need to record keys as they are pressed and make the API call with the query text.The html for the text box is this
<input id="query" data-bind="value: query, valueUpdate: 'keypress', event: { keypress: check }"/>
My assumption was that this will update the value in the viewmodel as soon as the key is pressed, and the
check
function will meanwhile call into the API. But the call is made to check( ) and the text box never gets populated when the user types. if the JS looks like this -function check() { alert("Hello"); }
For every key I press, hello pops up but the text box in the HTML UI does not show the key that was pressed/does not record which key was pressed. How do I record the key press and send the request simultaneously?