2

I can get selected text using this code in internet explorer:

var selectedText;
  // IE version
  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

but, how to delete selected text in TEXTAREA, for example, using JavaScript in both Google Chrome and Internet Explorer?

user2888402
  • 77
  • 1
  • 1
  • 9

3 Answers3

1

You might need to play around with the indexes a bit, but the below code should more or less work.

var originalText = document.getElementById("yourTextAreaId").value;
var selectedText = window.getSelection();
var startIndex = originalText.indexOf(selectedText) + 1;
var endIndex = startIndex + selectedText.length; 
var newText = originalText.substring(0,startIndex) + orignalText.substring(endIndex);
document.getElementById("yourTextAreaId").value = newText 
user2793390
  • 741
  • 7
  • 29
1

the answer given by user2793390 is not entirely correct! it doesn't work if the selected text is not the first occurrence of it in whole text!

I had a similar problem and i used another approach!

var selectedElemnt = document.getElementById("yourTextAreaId");
var selectedText = selectedElemnt.value;
var newText = selectedText.substr(0, selectedElemnt.selectionStart) + selectedText.substr(selectedElemnt.selectionEnd);
selectedElemnt.value = newText;
0

If you are dealing with IE v9 or later, use window.getSelection() which works across all modern browsers.

andleer
  • 22,388
  • 8
  • 62
  • 82