frequently ask ? : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

83 of 99 people (84%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I find and manipulate the selected text in an INPUT TYPE="text"/TEXTAREA?
How can I find and manipulate the text before and after a selection in an INPUT TYPE="text"/TEXTAREA?

Mar 10th, 2001 04:11
Martin Honnen,


IE4+ allows that by accessing
  document.selection.createRange()
and then manipulating that range object.
A complete example follows that creates three ranges, one with the text 
before the selection, one with the text that is selected, and one with 
the text after the selection:
<HTML>
<HEAD>
<TITLE>
selection manipulation in a text field with IE4+
</TITLE>
<SCRIPT>
function getContent (textInput) {
  content = new Object();
  if (document.selection) {
    var selectedRange = document.selection.createRange();
    if (selectedRange.parentElement() == textInput) {
      content.isSelected = true;
      content.selected = selectedRange.duplicate();
      content.beforeSelection = selectedRange.duplicate();
      content.beforeSelection.moveToElementText(textInput);
      content.beforeSelection.setEndPoint('EndToStart', selectedRange);
      content.afterSelection = selectedRange.duplicate();
      content.afterSelection.moveToElementText(textInput);
      content.afterSelection.setEndPoint('StartToEnd', 
content.selected);
    }
    else {
      content.isSelected = false;
      content.beforeSelection = textInput.createTextRange();
    }
  }
  else {
    content = null;
  }
  return content;
}
function showContent (content, form) {
  if (content && content.isSelected) {
    form.beforeSelection.value = content.beforeSelection.text;
    form.selected.value = content.selected.text;
    form.afterSelection.value = content.afterSelection.text;
  }
  else
    form.beforeSelection.value =
    form.selected.value =
    form.afterSelection.value = '';
}
function manipulateContent (content) {
  if (content && content.isSelected) {
    content.beforeSelection.text = 'BEFORE SELECTION:';
    content.afterSelection.text = ':AFTER SELECTION';
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
<INPUT TYPE="button" VALUE="show content"
       ONCLICK="showContent(getContent(this.form.textAreaName), 
this.form)"
>
<INPUT TYPE="button" VALUE="manipulate content"
       ONCLICK="manipulateContent(getContent(this.form.textAreaName));"
>
<BR>
<TEXTAREA NAME="textAreaName" ROWS="5" COLS="30">
Kibology for all.
All for Kibology.
</TEXTAREA>
<BR>
before selection:
<TEXTAREA NAME="beforeSelection" ROWS="5" COLS="30"></TEXTAREA>
<BR>
selected:
<TEXTAREA NAME="selected" ROWS="5" COLS="30"></TEXTAREA>
<BR>
after selection
<TEXTAREA NAME="afterSelection" ROWS="5" COLS="30"></TEXTAREA>
</FORM>
</BODY>
</HTML>