3

I'm searching for the following event, I need the number of the characters entered into a text box in a registration screen to appear automatically next to the same text box in JavaScript or jQuery.

it's a question from a beginner, thanks in advance.

Gintoki
  • 117
  • 2
  • 3
  • 7

2 Answers2

9

Listen for the input event and check the length of the textbox's value then.

$("#input").on("input", function() {
    $("#count").text(this.value.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input"> <span id="count">0</span>
Hydrothermal
  • 4,851
  • 7
  • 26
  • 45
2

IMHO, keypress should be the ideal event to look for character count.

$('#input').on('keypress', function(e) {
    var count = $(this).val().length;
    $('#span').text(count);
})   

Keypress vs. Keyup:

If i press and hold any character key for a few seconds, it'd enter few characters in input box and keyup event would give you a count of 1 for this because key was lifted only once. However, keypress would give the exact number of characters entered.

Bruno Monteiro
  • 4,153
  • 5
  • 29
  • 48
Tushar Shukla
  • 5,666
  • 2
  • 27
  • 41
  • 1
    What if I edit the text via the *Edit* menu rather than the keyboard? (Also, your explanation about not using `keyup` doesn't quite make sense, because the code you've shown doesn't count how many times the key was pressed/lifted, it directly tests the length of the current value.) – nnnnnn Dec 22 '16 at 03:39
  • @nnnnnn I didn't get editing text via Edit menu. Also, my explanation was not entirely in context of the question. May be my way of telling this was wrong but what i intended to tell is how keyup differs from keypress. – Tushar Shukla Dec 22 '16 at 10:56