views:

492

answers:

3

I'm trying to figure out if it's possible using Javascript to highlight a specific range of data in a text field.

textfield.select();

That ^^ works to select the entire text, but for all my googling I haven't stumbled upon a way to select, for example, characters 2 through 10 of the entered text. Is this possible?

Thanks!

+1  A: 

I think there is a very IE-specific way to do it that involves TextRange objects.

Here's some documentation on the TextRange object.

After posting I realized that this might only work on a textarea.

bobwienholt
+2  A: 

This is handled differently with IE vs everyone else.

Here is a reference guide with examples:

http://www.sxlist.com/techref/language/html/ib/Scripting_Reference/trange.htm

Diodeus
+1  A: 

This object will let you get, set & modify the selected region of a text box.

function SelectedText(input) {
  // Replace the currently selected text with the given value.
  this.replace = function(text) {
    var selection = this.get();

    var pre = input.value.substring(0, selection.start);
    var post = input.value.substring(selection.end, input.value.length);

    input.value = pre + text + post;

    this.set(selection.start, selection.start + text.length);

    return this;
  }

  // Set the current selection to the given start and end points.
  this.set = function(start, end) {
    if (input.setSelectionRange) {
      // Mozilla
      input.focus();
      input.setSelectionRange(start, end);
    } else if (input.createTextRange) {
      // IE
      var range = input.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', start);
      range.select();
    }

    return this;
  }

  // Get the currently selected region.
  this.get = function() {
    var result = new Object();

    result.start = 0;
    result.end = 0;
    result.text = '';

    if (input.selectionStart != undefined) {
      // Mozilla
      result.start = input.selectionStart;
      result.end = input.selectionEnd;
    } else {
      // IE
      var bookmark = document.selection.createRange().getBookmark()
      var selection = inputBox.createTextRange()
      selection.moveToBookmark(bookmark)

      var before = inputBox.createTextRange()
      before.collapse(true)
      before.setEndPoint("EndToStart", selection)

      result.start = before.text.length;
      result.end = before.text.length + selection.text.length;
    }

    result.text = input.value.substring(result.start, result.end);

    return result;
  }
}
Alex