43

I want to get the string length when a key is pressed like StackOverflow does.

Example of StackOverflow showing length

I have tried to do this with onblur, but it's not working. How do I do this?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143

11 Answers11

46

As for the question which event you should use for this: use the input event, and fall back to keyup/keydown in older browsers.

Here’s an example, DOM0-style:

someElement.oninput = function() {
  this.onkeydown = null;
  // Your code goes here
};
someElement.onkeydown = function() {
  // Your code goes here
};

The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)

P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you’ll see that it (incorrectly) counts as two characters.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • isn't even supported by standard Microsoft web fonts, so the likelihood of its usage is quite low, imho. EDIT: I could be wrong... It definitely doesn't appear in the answer body above, tho. –  Jul 25 '12 at 12:34
  • 3
    It’s just an example. Feel free to replace it with any astral (i.e. non-BMP) Unicode symbol. – Mathias Bynens Jul 25 '12 at 13:16
  • 4
    Thanks for pointing that out. Most english speakers overlook that problem. – Gaston Sanchez Jan 06 '14 at 03:38
  • Maybe it's very late but I would like to thank you for the information you have provided. It is more than a noob can think. – NullPoiиteя Mar 03 '16 at 01:37
15

UPDATE: Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

Use keyup event

var inp = document.getElementById('myinput');
var chars = document.getElementById('chars');
inp.onkeyup = function() {
  chars.innerHTML = inp.value.length;
}
<input id="myinput"><span id="chars">0</span>

EDIT:

Just a note for those that suggest keydown. That won't work. The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires after the character is added.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
  • 1
    I suggest you post your code here too - its more helpful when the target site it unavailable – Manse Jun 15 '12 at 08:08
  • This is outdated advice. [Use the more appropriate `input` event where available, then fall back to `keyup`/`keydown`.](http://stackoverflow.com/a/11046862/96656) Also, note that this doesn’t count the number of symbols in the string correctly. – Mathias Bynens Jun 15 '12 at 09:42
  • It might not be cutting edge, but it seems to work rather well. It's certainly not deprecated (at least not to my knowledge). –  Jun 15 '12 at 09:44
  • 3
    @bvukelic The `keyup` event won’t fire if you enter text by pasting (without using the keyboard), or by dragging text in; or when dictating text, for example. The `input` event does. As a bonus, the `input` event fires before you even lift up your key — making it feel much faster. – Mathias Bynens Jun 15 '12 at 13:08
6

You should bind a function to keyup event

textarea.keyup = function(){
   textarea.value.length....
} 

with jquery

$('textarea').keyup(function(){
   var length = $(this).val().length;
});
James
  • 13,571
  • 6
  • 61
  • 83
4

The quick and dirty way would be to simple bind to the keyup event.

$('#mytxt').keyup(function(){
    $('#divlen').text('you typed ' + this.value.length + ' characters');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type=text id=mytxt >
<div id=divlen></div>

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup )

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
Me.Name
  • 12,259
  • 3
  • 31
  • 48
3

function cool(d)
{
    alert(d.value.length);
}
<input type="text" value="" onblur="cool(this)">

It will return the length of string

Instead of blur use keydown event.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
3
 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

Lakshitha Udara
  • 153
  • 1
  • 15
2

I'm not sure what you mean by having tried it onblur, but to get the length of any string, use its .length property, so in the case of a textbox or textarea:

document.getElementById("textarea").value.length

Changing that ID, of course, to whatever the actual ID is.

Ashley Strout
  • 6,107
  • 5
  • 25
  • 45
  • The OP is talking about the event used - [`onblur`](https://developer.mozilla.org/en/DOM/element.onblur) – Manse Jun 15 '12 at 08:09
2

Basically: assign a keyup handler to the <textarea> element, in it count the length of the <textarea> and write the count to a separate <div> if its length is shorter than a minimum value.

Here's is an example-

var min = 15;
document.querySelector('#tst').onkeyup = function(e){
 document.querySelector('#counter').innerHTML = 
               this.value.length < min 
               ? (min - this.value.length)+' to go...'
               : '';
}
    
body {font: normal 0.8em verdana, arial;}
#counter {color: grey}
<textarea id="tst" cols="60" rows="10"></textarea>
<div id="counter"></div>
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
KooiInc
  • 119,216
  • 31
  • 141
  • 177
2
<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
    $(window).keydown(function (e) {
    //use e.which
    var length = 0;
    if($('#inputbox').val().toString().trim().length > 0)
    {
        length = $('#inputbox').val().toString().trim().length;
    }

    $('#length').val(length.toString());
  })
</script>
</body>
</html>
1

Leaving a reply (and an answer to the question title), For the future googlers...

You can use .length to get the length of a string.

var x = 'Mozilla'; var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');

/*"Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);

/*"The empty string has a length of 0" */

If you intend to get the length of a textarea say id="txtarea" then you can use the following code.

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.

Community
  • 1
  • 1
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
0

That's the function I wrote to get string in Unicode characters:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}
Nathan B
  • 1,625
  • 1
  • 17
  • 15