Programming

Character limit message to text & textarea fields in ACF

Sometimes, you might one to limit the character of text that user input in the text or textarea field to prevent user input from breaking the design of the website. This feature is included in the ACF plugin, but it doesn’t display any info when the character limit is reached.

 

Lets follow the following steps to display the message for maxlength in input fields

1. Load your js document in the admin page. I want to load my js file only for Alert Options Page.

function app_acf_admin_enqueue_scripts() {
    if($_GET['page']=='acf-options-alert-options') {
        wp_enqueue_script('acf-character-limit-js', plugin_dir_url(__FILE__) . 'assets/js/character-limit.js', [], false);
    }
}

add_action('acf/input/admin_enqueue_scripts', 'app_acf_admin_enqueue_scripts');

2. The following js code displays the character left in the input field when the user input the text in textarea field. Add this js code in your character-limit.js file and save the file.

window.onload = function() {
 //Select all the textarea with maxlength attribute
    var inputsWithLimit = document.querySelectorAll('textarea[maxlength]');
 // if your input field type is text : var inputsWithLimit = document.querySelectorAll('input[maxlength]');
// if maxlength is greater than zero
    if(inputsWithLimit.length > 0){
        inputsWithLimit.forEach(function(inputWithLimit){
	//create a DIV to display the msg	
            var hint = document.createElement('div');
            //hint.classList.add('txt-limit-hint'); // you can assign class for the created div
            hint.style.color = "#D93600"; // I  am adding  font color for the div 
            //https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
            inputWithLimit.parentNode.insertBefore(hint, inputWithLimit.nextSibling); //Insert Div right after the input field
              inputWithLimit.addEventListener('input', function(event){
		//Get the value from maxlength attribute 
                var inputMaxLength = event.target.getAttribute('maxlength');
		 //append the message in the div tag
                hint.innerHTML = 'Total Characters : '+inputMaxLength +'
 Remaining : ' + (inputMaxLength - event.target.value.length);
            });
        });
    }
}

Now, you can see the character limit message when you add the content in your ACF textarea field.

Views: 3799

Standard