Wednesday, May 28, 2014

Knockout EnterKey

There may be scenarios where you want to do something when user clicks enter key. Be it on a textbox or any control in the form. The html form has an ability to auto submit the form when user presses enter key. Also knockout has submit binding which allows you to handle enter key on a form. The html form submit and knockout’s submit binding may not be suitable in many scenarios. For example I am working on a SPA login page where I want to authenticate user after he presses enter key. As this is a SPA application there is no significance of form here. Even if I use form, the knockout submit event is not firing as I am using durandaljs.

In this blog I will show you how to write a custom binding which listens to the enter key in a form and raises the corresponding event. This custom binding can also be applied to a text box.

Creating an “enterKey” binding is very easy, all you need to do is listen to the enter key code and call the method that is associated with the binding. We will do this in the init callback. Here is the code

    ko.bindingHandlers.enterkey = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {

            ko.utils.registerEventHandler(element, "keyup", function (e) {
                if (e.keyCode === 13) {


As you see this a simple code where I am registering the key up event on the element, when the user presses enter key (keycode = 13), I am calling the associated method. Here is how I use the enterkey binding on a form

<form method="post" data-bind="enterkey: validate">

Please note that in some scenarios you may want your textboxes to update on a keyup as the enterkey does not trigger the update of the corresponding textbox.

<input type="text" placeholder="Username" data-bind="value: model.UserName, valueUpdate: 'keyup'"/>

No comments:

Post a Comment