JS implementation of text box focus in the last position _javascript tips

Source: Internet
Author: User

In a general program. When the programmer makes the content correctness of the input box, it usually likes to determine the focus box by judging the legality of the content.

Such as:

Copy Code code as follows:

if (obj.value== "") {
Obj.focus ();
return false;
}

This moves the focus to the input box when the input box is empty. This feature is very convenient to use. But there is a small problem ...

That's Obj.focus () when you move the focus to the input box, you move the text cursor (that is, a flashing vertical line) to the position of the first character of the input box ... As far as the above judgment is concerned. If there is no content in the text box ... Obj.focus just satisfies the point where we can just type in the text box without clicking the text box to keep the text focused ...

However, if there is already content in the text box ... But this content is illegal. Obj.focus () also moves the cursor to the position of the first character of the text box ... This will let the attention of the user experience of the designer depressed ... What we need is that the text box gets the focus, then the text cursor moves to the end of the text box, allowing the user to enter the content without clicking the text box. The input will be appended to the original content.

The following code can complete this small detail:

Copy Code code 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 is a great help to the designer in the details of the user experience ...

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.