Set Focus on a Textbox - MVC3

Solution 1:

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();

Solution 2:

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"})

Solution 3:

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!

Solution 4:

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();

Solution 5:

I'm using MVC4/Razor, and don't happen to have a Site.Master file in my project, However, I do have an _Layout.cshtml file that is applied to every page (Views/Shared/_Layout.cshtml), so I added this to an existing script in that file, as follows. This works well for me.

<script type="text/javascript">
    $(function () {
        $.ajaxSetup({
            // ajaxSetup code here...
            }
        });
        // Set the focus to the first textbox on every form in the app
        $("input[type=text]").first().focus();
    });
</script>