简体   繁体   English

如何将光标放在 ASP.NET 文本框的开头以获得焦点?

[英]How to place the cursor at the start of ASP.NET textbox on getting the focus?

I am fairly new to ASP, FYI.我对 ASP 相当陌生,仅供参考。 The textbox in question is for phone numbers, and I am using an Ajax MaskedEditExtender to create an input mask in the form "( ) - ___".有问题的文本框用于电话号码,我使用 Ajax MaskedEditExtender以“( ) - ___”形式创建输入掩码。

What is the issue now The input mask works fine, but when the user clicks into the box, the cursor just sits at whatever position they clicked at, in the middle of the input mask or wherever.现在有什么问题输入掩码工作正常,但是当用户单击框时,光标只是位于他们单击的任何位置,输入掩码的中间或任何地方。

What I need I need the cursor to be automatically positioned at the beginning (first character) of the textbox when the user clicks into it.我需要什么,我需要光标自动文本框的用户点击,当定位在开始(第一个字符)到它。 I am very familiar with how to do this in VBA using a GotFocus event.我非常熟悉如何使用 GotFocus 事件在 VBA 中执行此操作。 But there doesn't seem to be an event to handle this in ASP.但是在 ASP 中似乎没有处理这个的事件。 Is there JavaScript or some kind of setting I am missing?是否有我缺少的 JavaScript 或某种设置? I have searched but haven't been able to find anything to address this exactly.我已经搜索过,但无法找到任何可以准确解决此问题的内容。

I have included a link to a picture of what I am talking about, gotta earn some rep before I can embed...Thanks in advance!我已经包含了我正在谈论的图片的链接,在我嵌入之前必须获得一些代表......提前致谢!

You can set focus to your first textbox with JQuery您可以使用 JQuery 将焦点设置到您的第一个文本框

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var myFirstTextBox = $("#MyFirstTextBoxIdHere");
    $("myFirstTextBox ").focus();
});
</script>

This will autofocus on page load to your first textbox.这将自动聚焦页面加载到您的第一个文本框。

Try this out试试这个

<asp:TextBox runat="server" ID="txtMyBox" onFocus="setCursorToStart(this)"></asp:TextBox>
function setCursorToStart(x) {
        setTimeout(function() {
            x.setSelectionRange(0, 0);
        }, 0);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM