1. Home
  2. WP User Frontend Pro
  3. Tutorials
  4. Limiting character in text input & textarea

Limiting character in text input & textarea

Limiting characters is a required feature, but due to some problem in TinyMCE integration, the feature has been left out from WP User Frontend PRO. But it’s very easy to do that in text input and normal textareas. Here’s how you can do this.

Step 1: Initialize

We will first add this snippet in our themes functions.php, this will do the limitations.

function wpufe_limit_text() {
	?>
	<script type="text/javascript">
		(function($) {

			function limitText(field, maxChar){
			    var ref = $(field),
			        val = ref.val();

			    if ( val.length >= maxChar ) {
			        ref.val(val.substr(0, maxChar));
			    }
			}
      
      		// Insert Limitations here

		})(jQuery);
	</script>
	<?php
}

add_action( 'wp_footer', 'wpufe_limit_text' );

Step 2: Adding the limitations

We’ve mainly added the necessary code above, now it’s time to tell the code which fields to limit.

Every text input and textarea fields in WPUF has an unique ID and we can identify each fields by their ID. Every ID of custom fields is the same as their meta_key. If you are not sure the ID of a field, you can see your page source code (right click and View Page Source) and find the ID.

Screen Shot 2013-10-29 at 3.41.56 AM

Now as we’ve grabbed the CSS ID, in this case textarea_limit of a field, now we can add a limit on that field so that users won’t be able to enter more characters than we allow them.

$('#textarea_limit').on('keyup', function() {
    limitText(this, 10)
});

Insert this code after // Insert Limitations here in that code. Here we are adding a limitation of 10 characters in the textarea_limit ID (note the # (hash) sign, it must be before the ID).

Step 3: Finally!

So the full code will be (includes another field also with a ID user_bio):

function wpufe_limit_text() {
	?>
	<script type="text/javascript">
		(function($) {

			function limitText(field, maxChar){
			    var ref = $(field),
			        val = ref.val();

			    if ( val.length >= maxChar ) {
			        ref.val(val.substr(0, maxChar));
			    }
			}

            // Insert Limitations here
            $('#textarea_limit').on('keyup', function() {
                limitText(this, 10)
            });
      
      		$('#user_bio').on('keyup', function() {
                limitText(this, 250)
            });

		})(jQuery);
	</script>
	<?php
}

add_action( 'wp_footer', 'wpufe_limit_text' );

In this way, we could add limitations on various fields.

Was this article helpful to you? Yes 9 No 1

How can we help?