Joomla 4 Tips and Tricks: Form Textarea Counter

From Joomla! Documentation

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


Text area counters are commonplace javascript tools to help users with data entry. This tip comes from a component that has a lot of individual text area fields each with different character limits or no limits at all.

The form XML file[edit]

This is just one form field example to see how it works.

			class="required mycounter"

Notice the separate maxlength and data-maxlength values. The first is used by the browser to limit the field to that length. If it is omitted the text area length will not be limited and the counter will show values above the expected limit. The second is used by javascript to display the maximum number of characters to be entered.

The edit.php file[edit]

The last statement in the following loads the javascript file containing the counter code:

/** @var Joomla\CMS\WebAsset\WebAssetManager $wa */
$wa = $this->document->getWebAssetManager();

The Javascript File[edit]

In the layout used for this component there is room for the counters beneath the label. The counts appear on focus and are updated whenever there is a change.

var textareas = document.getElementsByClassName('opscounter');
if (textareas) {
	for (var i = 0; i < textareas.length; i++) {
		textareas[i].addEventListener('focus', updatecounter, false);
		textareas[i].addEventListener('input', updatecounter, false);

function updatecounter(event) {
	var ta = event.currentTarget;
	var min = ta.getAttribute('data-minlength');
	var max = ta.getAttribute('data-maxlength');
	if (!min || !max) {
	var label = + '-lbl';
	// is there an existing counter info div
	var counterid = label + '-counter';
	var counterdiv = document.getElementById(counterid);
	if (!counterdiv)  {
		var counterdiv = document.createElement("div");
		counterdiv.setAttribute("id", counterid);
	var contentlength = ta.value.length;
	counterdiv.innerHTML = `Min = ${ min }<br /> Max = ${ max }<br />Count = ${ contentlength }`;


Text Area Counter

Parent Links[edit]

Back to J4.x:Tips and Tricks for Joomla 4 Developers