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>
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