04 Votes

jQuery: Count characters from multiple input fields

Tip by Stefan Trost | 2013-01-19 at 19:03

In this tip, I show how to count the characters used over multiple input fields using jQuery and to display and keep up to date the result.

The HTML

These are the input fields and the field for the output of the result on our HTML page:

<input name="a" value="" class="count">
<input name="b" value="" class="count">
<input name="c" value="" class="count">
<input name="d" value="">

<p>Used characters: <span id="countdisplay">0</span></p>

Important: We assign the class "count" to all fields to be counted. These are the inputs "a", "b" and "c" in the example. We want to exclude the input field "d" from the counting, that is why we do not have assigned the class "count" to this field.

The used characters should be displayed in the field "countdisplay" later. We have assigned the ID "countdisplay" to this area, so that we can change the value easily.

The JavaScript/jQuery Code

Let's now have a look at our JavaScript/jQuery-Code:

$(document).ready(function() {
  $(".count").keyup(function() {
    var c = 0;
 
    $.each($(".count"), function() {
      c += $(this).val().length;
    });
	 
    $("#countdisplay").text(c);
  });
});

With $(".count"), we select all fields with the class "count", in other words, all fields that should be counted. We assign the function to count the fields and to display the result to the keyup-event of these fields.

After that, we set our count variable "c" to 0. Then, we go through all fields with the class "count" using $.each and we retrieve the length of their content with .val().length. We summarize the result in the variable "c".

At the end, we set the content of "countdisplay" to "c", so that the number of the characters is displayed there.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.