crecorn crecorn - 2 months ago 10
Javascript Question

javascript textarea count characters per line

I'm attempting to count the characters in each line of a textarea.

I've tried to adapt this code for counting syllable http://jsfiddle.net/5Zwkq/19/ with no success. Any help would be appreciated.



function $CharCount($input) {
$("[name=set_" + $input + "]").keyup(function() {

var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var char;
var $result;

for (var i = 0; i < arrayOfLines.length; i++) {
$content = arrayOfLines[i];
$result = $content.val().length;
tempArr.push($result);
}

$("[name=set_" + $input + "_content]").val(tempArr);

});
}

(function($) {
$CharCount("a");
})(jQuery);

<textarea rows="8" cols="3" class="alignright" name="set_a_syllable_count" readonly="readonly" /></textarea>
<textarea rows="8" cols="30" name="set_a"></textarea>




Answer

The .val() is causing an error in this line:

$result = $content.val().length;

Removing it properly counts the line lengths (at least in the calculations area).

As for the counter textarea bug, you just got the jQuery selector wrong. Rename your element set_a_syllable_count to set_a_content.

There is one more problem - when textarea is empty, it throws an error because you are checking an empty regexp result (null, to be precise). You simply have to prevent counting code to execute when there are no matched lines:

if (arrayOfLines !== null) { ... counting code ... }

Fixed code:

function $CharCount($input) {
  $("[name=set_" + $input + "]").keyup(function() {

    var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
    var tempArr = [];
    var $content;
    var char;
    var $result;

    if (arrayOfLines !== null) {
      for (var i = 0; i < arrayOfLines.length; i++) {
        $content = arrayOfLines[i];
        $result = $content.length;
        tempArr.push($result);
      }
    }

    $("[name=set_" + $input + "_content]").val(tempArr);

  });
}

(function($) {
  $CharCount("a");
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea rows="8" cols="3" class="alignright" name="set_a_content" readonly="readonly" /></textarea>
<textarea rows="8" cols="30" name="set_a"></textarea>

Comments