Js implements the focus at the last position in the text box

Source: Internet
Author: User

In general programs, programmers generally like to determine the focus frame by determining the content legality when checking the content correctness in the input box.

For example:
Copy codeThe Code is as follows:
If (obj. value = ""){
Obj. focus ();
Return false;
}

In this way, when the input box is empty, the focus will be moved to the input box... this function is very convenient to use... but there is a small problem...

That is obj. after the focus () is moved to the input box, the text cursor (that is, a flashing vertical line) is moved to the position of the first character in the input box... in terms of the above judgment .. if there is no content in the text box .. obj. the focus field can be used to directly input content in the text box without clicking the text box to make the text focus...

However, if there is already content in the text box .. however, this content is invalid. obj. focus () similarly move the cursor to the first character position of the text box .. this will make the designers who pay attention to the user experience depressed... what we need is the text box to get the focus, and then move the text cursor to the end of the text box, so that users can directly enter the content without clicking the text box .. the entered content will be appended to the original content ..

The following code completes this small detail:
Copy codeThe Code is as follows:
<Script language = "javascript">
Function getSelectPos (obj ){
Var esrc = document. getElementById (obj );
If (esrc = null ){
Esrc = event. srcElement;
}
Var rtextRange = esrc. createTextRange ();
RtextRange. moveStart ('character ', esrc. value. length );
RtextRange. collapse (true );
RtextRange. select ();
}
</Script>

This code will be of great help to designers in the detail of user experience...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.