Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS setting focus after adding to array/collection

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>
like image 778
Rick Hodder Avatar asked Nov 20 '25 16:11

Rick Hodder


1 Answers

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/

like image 165
LostInComputer Avatar answered Nov 23 '25 04:11

LostInComputer