David Najjár
David Najjár

Reputation: 11

Merging similar js functions into one function

I have 4 textarea boxes which take input, each of those boxes has a limit on the number of characters that it can take, the number of characters are display on the top right of each textarea, I have written an example at [code pen][1]

My question is since all 4 functions I use are pretty much do the same, they count the number of characters entered, the functions are called onkeyup is there a way to merge all 4 functions in to just one?

Appreciate any input.

enter code here[1]: http://codepen.io/dnajar/pen/RazZQW "code-pen"

Upvotes: 1

Views: 43

Answers (1)

d3l33t
d3l33t

Reputation: 890

Just abstract the common elements

function countChar(val, max, countSelector) {
    var len = val.value.length;
    if (len >= max) {
      val.value = val.value.substring(0, max);
    } else {            
      $(countSelector).text(len);
    }
  };

then use

onkeyup="countChar(this, 1000, '.charNum')"

Upvotes: 1

Related Questions