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?
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt , Shift , Ctrl , or Meta .
$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.
The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
For example, ko. applyBindings(myViewModel, document. getElementById('someElementId')) . This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.
valueUpdate = 'afterkeydown'
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
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