2

If there is highlighted text inside of a text input, how do I 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.

<input type='text' value='stackoverflow.com' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33

2 Answers2

9

selectionStart and selectionEnd are there to get selected text from input tag .. check the demo

$("#btnSelect").click(function () {
    document.getElementById('txtbox').setSelectionRange(6, 12);
});
$("#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;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='stackoverflow.com' id='txtbox' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>
Dhara
  • 1,914
  • 2
  • 18
  • 37
1

function removeText()
{
 document.getElementById('text1').value  = "";
}
<input type='text' value='stackoverflow.com' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove" onclick="removeText()">remove selected text</button>
RJParikh
  • 4,096
  • 1
  • 19
  • 36