3

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

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116
  • 1
    You need code for something really simple? Come on. Use your brains. – MortenMoulder Jul 16 '13 at 09:59
  • No need to get rude. You ask for simple code, which I already specified in the OP. It clearly says "I need to select some text" and "in a textarea with id=message" - how hard is it to figure out that textarea code? You ask me to show the code, but how would I show the code when I don't know the answer? Hence why I ask here. I can easily show the textarea code, which I just did, but getting the selected text + getting character count is something I don't know how to. Oh, and by the way: I tried to Google my way ahead, but found nothing. Keep your lame comments for yourself, and have a good day. – MortenMoulder Jul 16 '13 at 10:06
  • My bad - I missed the word selected. "Answer" deleted :) – Reinstate Monica Cellio Jul 16 '13 at 10:06
  • 1
    Look at this answer http://stackoverflow.com/a/5670157/581399 is that what you are looking for? – ihor marusyk Jul 16 '13 at 10:11
  • DKM: You're saying that I shouldn't post any questions here, yet that's pretty much what this is for... right? If you don't want me to post questions, then how about you start answering them? Then I could be out of here in the matter of seconds. – MortenMoulder Jul 16 '13 at 10:13
  • That's exactly what I was looking for. I'll modify it a bit - thanks, ihor marusyk! – MortenMoulder Jul 16 '13 at 10:14
  • Ladies, will you two keep the childish bickering out of it? You're both annoying and acting like 5 year olds. Just grow a pair and drop it. – Reinstate Monica Cellio Jul 16 '13 at 10:14
  • Try to use jCaret plugin. Check it out http://stackoverflow.com/questions/2377875/get-selected-text-in-a-textbox – Dima Kuzmich Jul 16 '13 at 10:16
  • hi, check my edit in my answer its working – Chandu Jul 16 '13 at 10:31

2 Answers2

4

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);
});
Chandu
  • 962
  • 2
  • 16
  • 33
2

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/

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68