最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove selected text from an input Text? - Stack Overflow

programmeradmin0浏览0评论

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' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>

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.' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>

Share Improve this question edited Apr 26, 2016 at 8:28 fdomn-m 28.6k8 gold badges37 silver badges67 bronze badges asked Apr 26, 2016 at 8:18 Waruna ManjulaWaruna Manjula 3,4971 gold badge37 silver badges35 bronze badges 3
  • 4 press backspace or delete – guradio Commented Apr 26, 2016 at 8:19
  • <input type='text' value='' id='text1' />. Set value blank. – RJParikh Commented Apr 26, 2016 at 8:20
  • Refer this: stackoverflow./questions/275761/… – Rayon Commented Apr 26, 2016 at 8:21
Add a ment  | 

2 Answers 2

Reset to default 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='stackoverflow.' 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.' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove" onclick="removeText()">remove selected text</button>

发布评论

评论列表(0)

  1. 暂无评论