MortenMoulder
MortenMoulder

Reputation: 6656

How to get character length of selected text with jQuery?

I need to select some text in a textarea with id="message" and then get the character count of that.

I'm assuming something with .length() is needed, but I'm not sure what it would require to actually get the selected text, and then use that to determine the length of it.

Thanks in advance

Upvotes: 3

Views: 8272

Answers (2)

Umesh Sehta
Umesh Sehta

Reputation: 10659

Try this:-

<textarea id="Editor"></textarea>
<input type="button" id="p" value="get text"/>

and in jquery:-

$('#p').on('click', function () {
var textComponent = document.getElementById('Editor');
var selectedText; 
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)    
alert("You selected: " + selectedText.length);
});

Demo http://jsfiddle.net/eQBYQ/4/

Upvotes: 2

Chandu
Chandu

Reputation: 1042

I think you are trying for this

$("#message").text().length;

Edit:

$("button").click(function(){
    var txt=document.getElementById("message");
    alert(txt.value.substr(txt.selectionStart, (txt.selectionEnd -txt.selectionStart)).length);
});

Upvotes: 4

Related Questions