Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Focus on a Textbox - MVC3

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>
like image 824
rk1962 Avatar asked Oct 22 '11 00:10

rk1962


3 Answers

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();
like image 113
Darin Dimitrov Avatar answered Nov 15 '22 19:11

Darin Dimitrov


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"})
like image 35
MaTya Avatar answered Nov 15 '22 20:11

MaTya


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!

like image 37
kaspur Avatar answered Nov 15 '22 20:11

kaspur