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>
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.