2
votes

I have viewmodel with an array of diagnosis codes. In my html I have a button data-bound to a click that adds a blank diagnosis code to the array. This all works.

What I cant figure out, is how to set focus to the dynamically added textbox when a code is added. What can I add :

<h3>Diagnosis Codes<input type="button" value="Add" data-bind="click:AddDiagnosisCode"/></h3>
<div data-bind="foreach:DiagnosisCodes">
    <div><input type="text"  data-bind="value:$data"/>
    </div>
</div>

<script type="text/javascript">
    function AddDiagnosisCode(item)
    {
        item.DiagnosisCodes.push("");
    }

    var vm = {
       "DiagnosisCodes": ["2345","6789"]
    };

    var viewModel = ko.mapping.fromJS(vm);     
     ko.applyBindings(viewModel);
</script>
2

2 Answers

10
votes

Use the built-in binding hasFocus and set it to true

<input type="text" data-bind="value:$data, hasFocus: true">

See http://jsfiddle.net/eT3Y8/

1
votes

It can be done with a custom binding. The harder part in this approach is to not focus on the boxes of the elements that are initially in the list. That's why I needed an extra isNew property, which is false for the already existing elements. I also used jquery to focus :) Fiddle: http://jsfiddle.net/hv9Dx/1/

html:

<h3>Diagnosis Codes<input type="button" value="Add" data-bind="click:AddDiagnosisCode"/></h3>
<div data-bind="foreach:DiagnosisCodes">
    <div><input type="text"  data-bind="value:value, focusOnCreate:isNew()"/>
    </div>
</div>

js:

var Record = function(value, isNew){
    var self = this;
    self.value = ko.observable(value);
    self.isNew = ko.observable(isNew || false);
}

var VM = function() {
    var self = this;    
    self.DiagnosisCodes = ko.observableArray([
        new Record("2345"),
        new Record("6789")]);
    self.enableFocus = ko.observable(true);
    self.AddDiagnosisCode = function(){
        self.DiagnosisCodes.push(new Record("", true));
    }
}

ko.bindingHandlers.focusOnCreate = {
    init:function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        if(valueAccessor()){
            $(element).focus();
        }
    }
}

     ko.applyBindings(new VM());