2016-04-26 86 views
1

如果文本输入内有高亮显示的文本,如何删除选定的文本?如何从输入文本中删除选定的文本?

我设置了一个小提琴,以显示我有多远,但我无法弄清楚如何删除给定的文本。

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

+4

按退格或删除 – guradio

+0

。设定值为空白。 – RJParikh

+0

请参阅:http://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript – Rayon

回答

7

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>

1

function removeText() 
 
{ 
 
\t 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>