How to use JavaScript to obtain the selected text in a text box
This article mainly introduces how to obtain the selected text in the text box by using JavaScript. examples show how to use javascript to obtain the selected text in the text box by using onclick. This article has some reference value. For more information, see
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:
The 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.