Set Focus on a Textbox - MVC3
You could provide an additional class to the containing div:
<div class="editor-field focus">
@Html.EditorFor(model => model.Amount)
@Html.ValidationMessageFor(model => model.Amount)
</div>
and then you could use a jQuery class selector:
$(function() {
$('.focus :input').focus();
});
This being said you seem to have multiple Amount
texboxes in a table and obviously only one can have the focus at a time. So assuming you want this to be the first, you could do this:
$('.focus :input:first').focus();
Open the /Views/Shared/Site.Master file and enter the following after the jquery script include this script:
<script type="text/javascript">
$(function () {
$("input[type=text]").first().focus();
});
</script>
This will set the focus to first textbox on every form in the app without writing any additional code!
with a html 5 compliant browser you set the autofocus
<input type="text" autofocus="autofocus" />
if you need IE support you need to do it with javascript
<input type="text" id=-"mytextbox"/>
<script type="text/javascript">document.getElementById('mytextbox').focus();</script>
in razor:
@Html.EditorFor(model => model.Amount,new{@autofocus="autofocus"})
The trick is that these input elements always have an id
attribute, which you can get as a string with Html.IdFor
. So you can focus the one you want with Javascript:
document.getElementById("@Html.IdFor(model => model.Amount)").focus();
Or, if you prefer jQuery:
$("#" + "@Html.IdFor(model => model.Amount)").focus();