/    Sign up×
Community /Pin to ProfileBookmark

Count characters in text area populated from database

I’m using the following javascript to count the characters in several text areas and it works fine when you start typing. I now need it to count the characters when the page loads. I’m guessing I need something other than keyup and also not sure if this will work with the text area being populated from a database. Can anyone help? Thanks

[CODE]
$(document).ready(function() {
$(‘.countThisA’).keyup(function() {
var cs = $(this).val().length;
$(‘#countA’).val(cs);
});

$(‘.countThisB’).keyup(function() {
var cs = $(this).val().length;
$(‘#countB’).val(cs);
});
});
[/CODE]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@toicontienDec 04.2013 — Sounds like a great argument for creating a jQuery plugin:

[code=html]
<input type="text" id="title" class="auto-counters">
<input type="text" id="title-counter" size="3">

<input type="text" id="sub-heading" class="auto-counters" data-autocounter-id="subhead_counter">
<input type="text" id="subhead_counter" size="3">

<textarea id="body" class="auto-counters"></textarea>
<input type="text" id="body-counter" size="3">

<script>
(function($) {
$.fn.autoCounter = function() {
var countCharacters = function countCharacters(field) {
var counterId = field.getAttribute("data-autocounter-id") || field.id + "-counter";
var $counter = $("#" + counterId);

if (!$counter.length) {
throw new Error("No counter was found for Id " + counterId);
}

$counter.val(field.value.length);
};

var handleKeyUp = function handleKeyUp(event) {
countCharacters(this);
};

var handleAutoCounterDestroy = function handleAutoCounterDestroy(event) {
$(event.target)
.unbind("keyup", handleKeyUp)
.unbind("autoCounter:destroy", handleAutoCounterDestroy);
};

return this.keyup(handleKeyUp)
.bind("autoCounter:destroy", handleAutoCounterDestroy)
.each(function() {
countCharacters(this);
});
};
})(jQuery);

$(function() {
$(".auto-counters").autoCounter();
});
</script>
[/code]
Copy linkTweet thisAlerts:
@drennanauthorDec 04.2013 — Thats awesome, exactly what I was looking for! Thanks for taking the time buddy ?
×

Success!

Help @drennan spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...