如何从输入文本中删除所选文本? [英] How to remove selected text from an input Text?

查看:112
本文介绍了如何从输入文本中删除所选文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文本输入中有突出显示的文本,该如何删除所选文本?

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>

推荐答案

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

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>

这篇关于如何从输入文本中删除所选文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆