JavaScript method to get selected text in text box_javascript skills
May 16, 2016 pm 04:13 PMThe example in this article describes how to obtain the selected text in the text box using JavaScript. Share it with everyone for your reference. The specific analysis is as follows:
The code here can be used to obtain the selection selected by the user in the text input box or textarea through the mouse.
Need to pay attention to the problem of ie.
The code is as follows:
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 button below</textarea><br />
<button onclick="alert(getFieldSelection(document.getElementById('a')))">button_click</button>
<br />
<strong>
Note: When using non-button elements to trigger the onclick event in IE, no result will be obtained. Because in IE, when a non-button element is clicked, the selection content in the entire page will be changed. This problem does not exist under Firefox and Opera. So the above (Span_onclick) will not be available under IE.
I hope this article will be helpful to everyone’s JavaScript programming design.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel.

How to enter bios on Colorful motherboard? Teach you two methods

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts)

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed!

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs)

How to set font size on mobile phone (easily adjust font size on mobile phone)

The difference between Go language methods and functions and analysis of application scenarios
