关于asp.net:使用javascript设置对文本框的关注

Set focus on textbox using javascript

在文本框中,用户可以输入日期。在OnChange事件中,我尝试使用javascript验证日期,如果它不是显示警报消息并将焦点设置在文本框上的有效日期。

在这里,当我输入无效日期并按tab时,会触发onchange事件,如果无效日期,则不会将焦点设置在texbox上,而是将焦点设置在表单中的下一个文本框上。

1
2
3
4
5
6
7
8
9
<asp:TextBox ID="txtDateOfBirth" runat="server"
    onchange="validateDate(this)"></asp:TextBox>

function validateDate(sender) {
    if (!Date.parseInvariant(sender.value,"MM/dd/yyyy")) {
        alert("date is incorrect");
        sender.focus();
    }
}


尝试使用onblur代替onchange

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
    check = function (sender) {
        if (sender) {
            alert("check");            
            sender.focus();
        }
    }

</asp:TextBox>

在上面的示例中,焦点将按预期返回给输入。