Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set focus to a text box Html.TextBoxFor - mvc 2

I'm trying to set focus on a text box which is generated in the following way:

<%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 })%>

I tried to use javascript which didn't help much :

   <script type="text/javascript">
       var txtBox = document.getElementById("Email");
       if (txtBox != null) txtBox.focus();
    </script>

How do I set focus to a text box Html.TextBoxFor in mvc 2 ?

like image 331
Liad Livnat Avatar asked Jun 01 '10 16:06

Liad Livnat


2 Answers

Where are you writing this javascript? You need to make sure that the DOM is loaded:

window.onload = function() {
    var txtBox = document.getElementById("Email"); 
    if (txtBox != null) { 
        txtBox.focus();
    }
};

Also HTML helpers might generate a different ID depending on the context: for example if you are calling the TextBoxFor inside an editor template.

Having said this it is not the solution I would recommend you. To solve all those problems I usually apply a css class to the textbox:

<%=Html.TextBoxFor(
    model => model.Email, 
    new { @class = "email", maxsize = "190" }) %>

where email class is defined like this:

.email {
    width: 190px;
    border: 0;
}

and then use a popular javascript framework to set the focus when the DOM is ready:

$(function() {
    $('input.email').focus();
});
like image 88
Darin Dimitrov Avatar answered Sep 27 '22 19:09

Darin Dimitrov


you can use autofocus in HTML5 . <%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 ,autofocus = "autofocus" })%>

like image 22
AR M Avatar answered Sep 27 '22 19:09

AR M