How can I set focus on "Amount" textbox on page load for the following Razor code in MVC3?
<tr>
<th>
<div class="editor-label">
@Html.LabelFor(model => model.Amount)
</div>
</th>
<td>
<div class="editor-field">
@Html.EditorFor(model => model.Amount)
@Html.ValidationMessageFor(model => model.Amount)
</div>
</td>
</tr>
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();
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"})
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With