I asked this question and got a great answer, so now I have a dynamic template in knockout, which works great, except in IE I can't get the dynamic template to set the focus in one of the input fields when the popup is rendered. Adding the autofocus to the tem,plate script text works in chrome, but I'd like it to work in IE as well, but can't seem to get it to.
modal = {
header: ko.observable("This is a modal"),
//this is now just the name of the template
body: ko.observable('bodyTemplateA'),
// ...
};
And then in your binding, do
<div class="modal-body" data-bind="template: { name: body }">
</div>
and then of course define all of your needed templates separately:
<script id="bodyTemplateA" type="text/html">
Name:<input id='workflowname' autofocus type="text" data-bind="value: paramName" /><br/>
Type:<input type="text" data-bind="value: paramType" /><br />
</script>
I tried using the knockout hasfocus binding:
<script id="bodyTemplateA" type="text/html">
Name:<input autofocus type="text" data-bind="value: paramName, hasfocus: true" /><br/>
Type:<input type="text" data-bind="value: paramType" /><br />
</script>
but that doesn't seem to work.
I also tried adding some jquery into the function which shows the form:
self.showStepModal = function () {
self.newStepModal.show(true);
//tried both of the following lines but neither seems to work...
$('[autofocus]:not(:focus)').eq(0).focus();
$('#workflowname').focus();
};
What can I do to set the focus into the input tagged with autofocus after the template has been rendered?
I traced your prior questions leading to this (here and here), and saw that you were using Bootstrap for the modal. I am answering this question under that context.
Within a Modal
To get it working with a modal, the key is to point the
hasFocus
binding to an observable (isFocused
in this example), and toggle its value after the modal has rendered, via theshown.bs.modal
event.See fiddle: http://jsfiddle.net/JasperTey/CRnXW/.
HTML
JavaScript
Non-modal Case
When using a knockout template in a regular non-modal scenario, the hasFocus binding should work as per your original expectations. Either explicitly via
hasFocus: true
, orhasFocus: isFocused
whereisFocused
is initialized totrue
.See fiddle of non-modal example: http://jsfiddle.net/JasperTey/4gzKu/