Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove selected text from an input control?

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();
        }
    }
});
like image 396
Smeegs Avatar asked Nov 01 '25 02:11

Smeegs


1 Answers

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

like image 150
dc5 Avatar answered Nov 02 '25 17:11

dc5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!