Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using keypress event in knockout JS

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?

like image 892
divyanshm Avatar asked Sep 19 '13 14:09

divyanshm


People also ask

How do you keypress an event?

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 .

What is $root in knockout?

$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.

What is keypress function?

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).

What is Ko applyBindings?

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.


1 Answers

  1. make sure query is an observable
  2. use valueUpdate = 'afterkeydown'
  3. 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

like image 89
egucciar Avatar answered Sep 24 '22 13:09

egucciar