How do I remove selected text from an input control?

爷,独闯天下 提交于 2021-01-27 23:31:27

问题


Basically, I want to be able to detect:

  1. if there is highlighted text inside of a text input
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!