Knockout.js input focus after clicking

I am trying to adjust the focus to a knockout entry after the click event is fired, but cannot find a clean way to handle it without communicating with the DOM. Here is the JS code that I have:

(function() { var vm = { text: ko.observable(), items: ko.observableArray([]) } vm.addItem = function() { vm.items.push(vm.text()); vm.text(null); } ko.applyBindings(vm); }()); 

This is my DOM:

 <input type="text" data-bind="value: text" /> <a href="#" data-bind="click: addItem">Send</a> <ul data-bind="foreach: items"> <li data-bind="text: $data"></li> </ul> 

Here is a JsFiddle example: http://jsfiddle.net/srJUa/1/

What I want it to focus on input after vm.addItem completes. Any idea how this can be done cleanly, for example using custom knockout bindings?

+8
source share
2 answers

Knockout has a built-in focus control snap: hasfocus snap .

So, you just need to create a boolean property on your view model and associate it with your input and set the property to true if you want to focus the input.

Or in your case, you can bind directly to the text property, so when it has no text, it should have focus:

 <input type="text" data-bind="value: text, hasfocus: !text()" /> 

JSFiddle demo.

+14
source share

Ok, I solved the problem using hasfocus binding:

 (function() { var vm = { text: ko.observable(), items: ko.observableArray([]), isFocused: ko.observable() } vm.addItem = function() { vm.items.push(vm.text()); vm.text(null); vm.isFocused(true); } ko.applyBindings(vm); }()); 

HTML:

 <input type="text" data-bind="value: text, hasfocus: isFocused" /> <a href="#" data-bind="click: addItem">Send</a> <ul data-bind="foreach: items"> <li data-bind="text: $data"></li> </ul> 

Working example: http://jsfiddle.net/srJUa/2/

Not sure if this is the best way.

+4
source share

All Articles