Simple way to count characters using .keyup in jQuery
Asked Answered
S

2

12
<input type="text" />

How can I write the number of characters from input on .keyup in JavaScript/jQuery?

Sales answered 4/2, 2012 at 16:24 Comment(0)
C
37
$('input').keyup(function() {
    console.log(this.value.length);
});

keyup is a shortcut method for bind('keyup').
And as of jQuery version 1.7, all of the above are deprecated we are encourage to use the on method to bind events, meaning that the code should look like this:

$('input').on('keyup', function() {
    console.log(this.value.length);
});
Correy answered 4/2, 2012 at 16:27 Comment(2)
Too much jQuery. this.value.length is also sufficient (instead of $(this).val().length).Henden
Many thnx Answers should also have been able to be bookmarked : )Gonadotropin
S
6

Example - This will alert out the number of characters

$('#textBoxId').bind('keyup', function(e){

     alert($(this).val().length);

});

This obviously assumes that the text box has an id of textBoxId. Otherwise change selector iof don't want to give it an id for some reason

Single answered 4/2, 2012 at 16:28 Comment(1)
That would only work if the input had an id of textbox. <input type="text" id="textbox" />Wont

© 2022 - 2024 — McMap. All rights reserved.