如何将焦点设置为文本框Html.TextBoxFor - mvc 2

时间:2010-06-01 16:11:13

标签: javascript html asp.net-mvc focus html-helper

我正在尝试将焦点设置在以下列方式生成的文本框中:

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

我尝试使用javascript并没有多大帮助:

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

如何将焦点设置为mvc 2中的文本框Html.TextBoxFor?

2 个答案:

答案 0 :(得分:29)

你在哪里写这个javascript?您需要确保加载DOM:

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

HTML帮助程序也可能根据上下文生成不同的ID:例如,如果您在编辑器模板中调用TextBoxFor

说完这个不是我推荐你的解决方案。为了解决所有这些问题,我通常将css类应用于文本框:

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

其中email类的定义如下:

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

然后使用popular javascript framework在DOM准备就绪时设置焦点:

$(function() {
    $('input.email').focus();
});

答案 1 :(得分:7)

您可以在HTML5中使用自动对焦。 <%=Html.TextBoxFor(model => model.Email, new { style = "width:190px;Border:0px", maxsize = 190 ,autofocus = "autofocus" })%>