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 ?
Where are you writing this javascript? You need to make sure that the DOM is loaded:
Also HTML helpers might generate a different ID depending on the context: for example if you are calling the
TextBoxForinside 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:
where
emailclass is defined like this:and then use a popular javascript framework to set the focus when the DOM is ready: