I have an observable array, bound to the list of contenteditable divs. I have an ‘add’ button. On click I add an object to array and want to give focus to the corresponding div.
<ul id='list' data-bind="foreach: array">
<li>
<div contenteditable="true" data-bind="text: $data.text"></div>
</li>
</ul>
<div id="add">+</div>
javascript
var viewModel = {
array: ko.observableArray([])
};
ko.applyBindings(viewModel, document.getElementById('list'));
document.getElementById('add').onclick = function (evt) {
var newObject = {text : ''};
viewModel.array.push(newObject);
// give focus to the newly created div
};
It is possible to get the observable data having DOM element ko.dataFor(dom). How to get DOM by data?
Thanks
You can’t get the DOM element from the data itself. In this scenario though, you could use the
hasfocusbinding to move focus to the new element. Docs here: http://knockoutjs.com/documentation/hasfocus-binding.htmlEven just placing
hasfocus: trueon a new element will do the trick.Otherwise, if you don’t want the focus to be applied for the initially rendered elements, then you could pass in a flag for the newly created element like:
view model:
Sample: http://jsfiddle.net/rniemeyer/jnHK8/