KnockoutJS Focus Binding

Till now, we have covered most of the form field bindings. We studied, click binding, event bindings, if/ifnot binding and enable/disabled binding etc. In this article we shall study another type of binding i.e KnockoutJS Focus Binding. This type of binding binds a focus-able HTML DOM elements such as a text field or a button with a javascript view model parameter. The binding is two way. If the HTML element is focused, the corresponding view model parameter is assigned a true. Similarly, if in the code, the view-model parameter has a false value, the associated HTML element is de-focused. KnockoutJS focus binding is extremely useful in scenarios where form elements are dynamically generated and you want to set default focus to one of the form field. Take a look at the following example to see KnockoutJS Focus binding in action.

KnockoutJS Focus Binding Example

<!DOCTYPE html>
<script src=""></script>


    <label><input type="checkbox" data-bind="checked: Male" /> Male</label>
<div data-bind="if: Male">Student is a Male.</div>
    function StudentModel() {
    this.Male = false;

ko.applyBindings(new StudentModel());

Download the code Try the code

Take a careful look at the above piece of code. It contains a text box with a binding “hasFocus.” This is how you add focus to the element. The value for this binding can be true or false. In the above code we bind the focus of this text box with StudentModel parameter “hasFocus.” The value of “hasFocus” parameter is set to false by defult. Next in on the click event of the button in HTML view, we call the setFocus method of javascript. The setFocus function basically sets the value of hasFocus parameter to true.

Now open the above page, in the browser. You should see a text-box and button. By default the focus is at somewhere else. However if you click button, the “setFocus” function executes which sets the value of “hasFocus javaScript variable to true. Therefore the textbox becomes focused and the statement after the button becomes visible.”

<<< KnockoutJS Checked BindingKnockoutJS Value Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .