This is an example for adding a counter to the inputing texts of tags <textarea> and <input>:

<html>
 
<head>
  <title>Text Counter</title>
 
  <script type="text/javascript">
  function text_counter(textfield_id,counter_id,count){
    count = parseInt(count);
 
    document.getElementById(counter_id).innerHTML = count;
 
    document.getElementById(textfield_id).onpropertychange = function(){
        text_count_changed(textfield_id,counter_id,count);
    }
  }
 
  function text_count_changed(textfield_id,counter_id,count){
    if(count-parseInt(document.getElementById(textfield_id).value.length)<0){
        document.getElementById(textfield_id).value = document.getElementById(textfield_id).value.substr(0,count);
    }
 
    document.getElementById(counter_id).innerHTML = count-parseInt(document.getElementById(textfield_id).value.length);
  }
  </script>
</head>
 
<body>
<p>
<script type="text/javascript">inputtext_approving_chars_count = 10;</script>
<input type="text" id="inputtext" oninput='text_count_changed("inputtext","inputtext_counter",inputtext_approving_chars_count);'> <span id="inputtext_counter"></span>
<script type="text/javascript">text_counter("inputtext","inputtext_counter",inputtext_approving_chars_count);</script>
</p>
 
<p>
<script type="text/javascript">textfield_approving_chars_count = 255;</script>
<textarea id="textfield" cols="50" rows="10" oninput='text_count_changed("textfield","textfield_counter",textfield_approving_chars_count);'></textarea> <span id="textfield_counter"></span>
<script type="text/javascript">text_counter("textfield","textfield_counter",textfield_approving_chars_count);</script>
</p>
 
</body>
 
</html>
Share

3 Comments on Text counter by JavaScript

  1. very cool & good js, thank you very much for sharing.

    Can you share this code on my JavaScript library?

    Awaiting your response. Thank

  2. Useful information. Fortunate me I discovered your website unintentionally, and I’m stunned why this coincidence did not took place earlier! I bookmarked it.

Leave a Reply

Info