-1

I have texbox in my page and I am trying to get the length from the textbox. I know how to get the length in IE, but the following code is not working in FF and chrome.

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(obj)
{
alert("mouse up");
var r=window.getSelection().createRange();
alert(r.text.length);

}
</script>
</head>
<body>

<textarea id="myArea" cols="30" spellcheck="false" onmouseup=myFunction(this)>Select some text within this field.</textarea>


</body>
</html>
Perseus
  • 1,418
  • 4
  • 26
  • 53
  • 2
    See here: http://stackoverflow.com/a/5072684/1296553 – Rodrigo Siqueira Apr 18 '13 at 16:31
  • 2
    Duplicate of [window.getSelection() of textarea not working in firefox?](http://stackoverflow.com/questions/20419515/window-getselection-of-textarea-not-working-in-firefox), which has better answers. [window.getSelection not working on textareas in Firefox is a fabulously old bug in FF](https://bugzilla.mozilla.org/show_bug.cgi?id=85686). – Dan Dascalescu Sep 04 '15 at 23:03

1 Answers1

3

Textareas and text inputs have a different selection API from the main document selection. Use selectionStart and selectionEnd properties of the textarea/input.

function myFunction(obj) {
    var selectedText = obj.value.slice(obj.selectionStart, obj.selectionEnd);
    alert(selectedText);
}

If you need support for IE <= 8, there is a different API again. See Caret position in textarea, in characters from the start

Community
  • 1
  • 1
Tim Down
  • 292,637
  • 67
  • 429
  • 506