【问题标题】:How to remove selected text from an input Text?如何从输入文本中删除选定的文本?
【发布时间】:2016-08-19 22:35:49
【问题描述】:

如果文本输入内有突出显示的文本,如何删除选定的文本?

我设置了一个小提琴来显示我走了多远,但我不知道如何删除给定的文本。

<input type='text' value='stackoverflow.com' id='text1' />
<br />
<button id="btnSelect">select text</button>
<button id="btnRemove">remove selected text</button>

【问题讨论】:

标签: javascript php jquery html


【解决方案1】:

selectionStartselectionEnd 可以从input 标签中获取选定的文本。 查看演示

$("#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>

【讨论】:

    【解决方案2】:

    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>

    【讨论】:

    • OP 只想删除选定的文本而不是整个值。
    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多