JavaScript to obtain the selected text in the text box, javascript text box

Source: Internet
Author: User

JavaScript to obtain the selected text in the text box, javascript text box

This example describes how to use JavaScript to obtain the selected text in a text box. Share it with you for your reference. The specific analysis is as follows:

The code here can be used to obtain the selector selected by the user in the text input box or textarea.
You need to pay attention to ie issues.

The Code is as follows:
Copy codeThe Code is as follows: <script type = "text/javascript">
Function getFieldSelection (select_field)
{
Word = '';
If (document. selection ){
Var sel = document. selection. createRange ();
If (sel. text. length> 0 ){
Word = sel. text;
}
}
Else if (select_field.selectionStart | select_field.selectionStart = '0 '){
Var startP = select_field.selectionStart;
Var endP = select_field.selectionEnd;
If (startP! = EndP ){
Word = select_field.value.substring (startP, endP );
}
}
Return word;
}
</Script>
<Textarea id = "a" rows = "3" cols = "20"> select me and click the following button </textarea> <br/>
<Button onclick = "alert (getFieldSelection (document. getElementById ('A')"> button_click </button>
<Br/>
<Strong>

Note: When the non-button element onclick is used in IE to trigger the event, no results will be obtained. In IE, when a non-button element is clicked, the selection content on the entire page will be changed. This problem does not exist in firefox and opera. Therefore, the above (Span_onclick) will be unavailable in IE.

I hope this article will help you design javascript programs.

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.