Reputation: 3477
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>
Upvotes: 2
Views: 3978
Reputation: 4166
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>
Upvotes: 1
Reputation: 1972
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>
Upvotes: 9