问题
Basically, I want to be able to detect:
- if there is highlighted text inside of a text input
- How to remove the selected text
I set up a fiddle to show how far I got, but I can't figure out how to remove the given text.
http://jsfiddle.net/z36Px/
Here is my markup
<input type='text' value='Hello World!' id='txtbox' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>
and my javascript
$("#btnSelect").click(function () {
document.getElementById('txtbox').setSelectionRange(6, 12);
});
$("#btnRemove").click(function () {
if (window.getSelection) {
if (window.getSelection().deleteFromDocument) {
window.getSelection().deleteFromDocument();
}
}
});
回答1:
Depending on browser compatibility (ie9+ and others) you could use selectionEnd, selectionStart:
$("#btnRemove").click(function () {
var ele = document.getElementById('txtbox');
var text = ele.value;
text = text.slice(0, ele.selectionStart) + text.slice(ele.selectionEnd);
ele.value = text;
});
Working Fiddle in Chrome
来源:https://stackoverflow.com/questions/18133776/how-do-i-remove-selected-text-from-an-input-control