Saint Robson
Saint Robson

Reputation: 5525

Count characters from textarea when document ready and keyup

I want to count how many characters inside textarea (if any) when the page is loaded on the screen for the first time. then I also want to show it when user add more characters or delete some of it.

My HTML Code :

<form>
  <div class="form-group">
    <textarea id="textBox" class="form-control" rows="10">Hello world</textarea>
    <div id="charNum"></div>
  </div>
</form>

and I have this jQuery script :

function countChar() {
    var len = val.value.length;
    $('#charNum').text(len+' characters');
};

$(document).ready(function(){
    countChar();
    $('#textBox').change(countChar);
    $('#textBox').keyup(countChar);
});

but it's not displaying result as I wanted, what did I do wrong here?

Upvotes: 0

Views: 1388

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Here's another version that allows using this inside countChar()

function countChar() {
    // since only used as event handler callback reference have access to `this`
    var len = this.value.length;
    $('#charNum').text(len + ' characters');
};

$(document).ready(function () {
    // trigger event on page load to set first count
    $('#textBox').change(countChar).change();
    $('#textBox').keyup(countChar);

    /* or combine both events and trigger one of them on page load */
     $('#textBox').on('change keyup', countChar).change();

});

Since the function is only ever used as a reference for event handler it will automatically expose this as the element instance

DEMO

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

There are 2 problems in your script

  1. A syntax issue with a unclosed '
  2. The way how you are reading the textarea value is wrong, use a id-selector to get the textarea and then use .val() to read the value

function countChar() {
  var len = $('#textBox').val().length;
  $('#charNum').text(len + ' characters');
};

$(document).ready(function() {
  countChar();
  $('#textBox').change(countChar);
  $('#textBox').keyup(countChar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <textarea id="textBox" class="form-control" rows="10">Hello world</textarea>
    <div id="charNum"></div>
  </div>
</form>

Upvotes: 3

Related Questions