How to Limit Character in Text Input and Text Area
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.
?>
<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.
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.
limitText(this, 10)
});[/js]
Insert this code after the
code. Here we are adding a limitation of ch
aracters 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
):
?>
<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.