Reputation: 559
I'm using knockout.js in MVC3 application. I'm quite new to knockout so the question may seem a little bit dumb.
I want to have an input to be focused when the page loads. The things I already tried, are:
<input type="text" class="text-field" data-bind="attr: { autofocus: autofocus }
and
<input type="text" class="text-field" data-bind="hasFocus: true
but both didn't help. What am I doing wrong?
Just small update. This is the whole view of the input.
<input type="text" class="text-field" data-bind="value: RegistrationNumber, valueUpdate: 'blur', enterKey: $root.proceedToServicestPage, hasFocus: true" />
I thought that the issue could be because of the order of binder calls and tried to place hasFocus:true in the different positions(from first to last binders). This didn't help as well
Upvotes: 1
Views: 1394
Reputation: 11
Coming very late to the party, but maybe it will help someone. As @jeroen says, the attribute has to be set within the knockout binding. In fact autofocus
can be set there - it's just a question of correct syntax. I was able to solve it with either of the following:
data-bind="attr: { autofocus: 'autofocus' }
which gives an attribute in the resulting markup of autofocus="autofocus"
data-bind="attr: { autofocus: '' }
which gives an attribute in the resulting markup of just autofocus
either of these worked in Chrome for me
Upvotes: 1
Reputation: 63719
You cannot use autofocus
attribute, because this is done by the browser when the document is loaded, which is before your JavaScript (Knockout) has had a chance to run to set the attribute.
Your second option should work. I can repro using this View:
<input type="text" value="Aaaaaaa" data-bind="hasFocus: false" /><br />
<input type="text" value="Be Selected!" data-bind="hasFocus: true" /><br />
<input type="text" value="Cccccc" data-bind="hasFocus: false" />
And this JS:
ko.applyBindings({});
See this fiddle for a demo.
Upvotes: 1