Joomla 4 Tips and Tricks: Form Textarea Counter

From Joomla! Documentation

Revision as of 04:28, 7 May 2021 by Ceford (talk | contribs) (→‎The Javascript File)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Introduction[edit]

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.

		<field 
			name="description" 
			type="textarea" 
			label="COM_MYCOMPONENT_CAMP_DESCRIPTION_LABEL" 
			description="COM_MYCOMPONENT_CAMP_DESCRIPTION_DESC"
			class="required mycounter"
			maxlength="800"
			data-minlength="50"
			data-maxlength="800"
			cols="60"
			rows="6" 
			required="true"
			/>

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();
$wa->useScript('keepalive')
	->useScript('form.validate')
	->useScript('com_mycomponent.camp');

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) {
		return;
	}
	var label = ta.id + '-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);
		document.getElementById(label).append(counterdiv);
	}
	var contentlength = ta.value.length;
	counterdiv.innerHTML = `Min = ${ min }<br /> Max = ${ max }<br />Count = ${ contentlength }`;
}

Result[edit]

Text Area Counter

Parent Links[edit]

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