How to Limit Character in Text Input and Text Area

A- A+

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

Step 1: Initialize

We will first add this snippet to our themes; this will set the limitations.

[php] 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' );
[/php]

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 field in WPUF has a unique ID, and we can identify each field by its ID. Every ID of custom fields is the same as theirmeta_key. If you are not sure of the ID of a field, you can see your page source code (right-click and view the page source) and find the ID.

Screen Shot 2013-10-29 at 3.41.56 AM

Now that we've grabbed the CSSID, in this case of a field, we can add a limit to that field so that users won't be able to enter more characters than we allow them.

[js]$(‘#textarea_limit').on(‘keyup', function() {
limitText(this, 10)
});[/js]

Insert this code after the code. Here we are adding a limitation of characters in thetextarea_limit ID (note the (hash) sign; it must be before the.

Step 3: Finally!

So the full code will be (which include another a field with an ID user_bio):

[php] 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' );
[/php]

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