Stop users from entering text into an textarea field after a certain amount of characters have been entered

270
December 10, 2016, at 11:47 PM

I'm trying to stop users from entering data into a textarea after the character count has reached its limit. And is it possible for the character count to keep track of how many characters have been entered even after the page has been refreshed?

Jquery

    $('.character-count').text('4000 characters left');
    $('#description').keyup(function(){
        var max = 4000;
        var len = $(this).val().length;
        var ch = max - len;
        $('.character-count').text(ch + ' characters left');
    });
Answer 1

Try this:

var max = 10;
$('#description')
.keydown(function(event){
    if (event.keyCode != 8 && event.keyCode != 46 && $(this).val().length >= max) {
        event.preventDefault();
    }
})
.keyup(function(){
    var $this = $(this),
        val = $this.val().slice(0, max),
        val_length = val.length,
        left = max - val_length;
    $('.character-count').text(left + ' characters left');
    $this.val(val);
});

After each keyup textarea value is cut off after max symbols.
Keydown event is blocking after value length reached max,
but you can still press backspace (8) or delete (46) keys.

Answer 2

use local storage in order to deal with later use

HTML

<textarea name="userText" id="description" cols="30" rows="10"></textarea>
<div class="character-count"></div>

jQuery

    $(function(){
    var comment = $('#description');
    var val = localStorage.getItem( comment.attr('id') ),
        max = 4000,
        len = val.length,
        left = ( max - len ) ;
    // if the value exists, set it
    if (val) {
        comment.val(val);
        $('.character-count').text( left + ' Character(s) left');
    }
});
$('#description').on('keyup', function (e) {
    var $this = $(this),
        max = 4000,
        val = $this.val(),
        val_length = val.length,
        remain = ((max - val_length)>=0)?(max - val_length):0;
    $('.character-count').text(remain + ' Character(s) left');
    if( val_length > max ){
        $this.val(val.slice(0,max));
    }
    // let's check if localStorage is supported
    if (window.localStorage) {
        localStorage.setItem($(this).attr('id'), $(this).val());
    }

});

SEE DEMO

Answer 3

There is a built-in HTML5 attribute maxlength, which will restrict the count of entered symbols. There is no need to reinvent it yourself:

$("input").on('input', function() { 
  var left = this.maxLength - this.value.length; 
  $("span").text(left + " characters left"); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" maxlength="5"/> 
<span>5 characters left</span>

Also, if you use keyup handler, then the user can easily type your text somewhere else and paste as many characters as he wants. Use input.

Talking about "to keep track of how many characters have been entered even after the page has been refreshed", you may use cookies, but it is a doubtful feature. Any user can easily replace or empty any cookies or other local storage. If this limitation is really important, implement it server-side.

Answer 4

You can save the entire text entered by the user in the cookie as suggested by coolguy and on refresh you can just retrieve the cookie data and display in the text area as well as the character count tracker.

<script>
        $(function () {
            var descText = $.cookie('description');
            var descTextArea = $('#description');
            var maxLength = descTextArea.data('maxLength');
            if (descText) {
                descTextArea.text(descText);
                $('.character-count').text((maxLength - descText.length) + ' characters left');
            }
            else {
                $('.character-count').text(maxLength + ' characters left');
            }
            descTextArea.keydown(function (event) {
               var max = maxLength;
               var len = $(this).val().length;
               var ch = max - len;
               if (ch < 0 ) {
                  event.preventDefault();
                  return false;
               }
               $('.character-count').text(ch + ' characters left');
               $.cookie('description', $(this).val(), {path: '/'});
            });
        });
    </script>

Using keydown after referring answer by legotin. HTML file is:

<textarea id="description" data-max-length="4000"></textarea>
<span class="character-count"></span>

I am using jquery.cookie plugin.

Answer 5

Use e.preventDefault() to stop handling.

e.preventDefault();

$('.character-count').html('20 characters left');
var len = 0;
var max = 20;
$('#description').keydown(function (e) {
    var code = e.keyCode;
    if(len == max && code != 8)
    {
        e.preventDefault();
        return false;
    }
    len = $(this).val().length;
    var ch = max - len;
    $('.character-count').text(ch + ' characters left');
});

try this Fiddle

Rent Charter Buses Company
READ ALSO
Remove item from a list on second select

Remove item from a list on second select

I would like to remove an item from drop down list not on first time, but after selecting a second item, in the bellow example if I select option1 will remove option1, but I need to select option1 (nothing will be removed), while selecting option4 (now option1...

342
count size array show in order S to L

count size array show in order S to L

i am making a count size check , so basic is user choice all the size they need and show it the total size they had choice, but i want the size show in order , start from "S , M , L" but my array show it mixed , how to i make my array show it in order

436
Autocomplete to return main word for group of words

Autocomplete to return main word for group of words

I am using jQuery autocomplete - https://jqueryuicom/autocomplete/ and have this working for a dropdown:

247
tracker bar with css and html won&#39;t show on my page

tracker bar with css and html won't show on my page

I tried to create a tracker bar that will show steps in my pageI tried this code in jsfiddle and it looks good, but my problem is when I use it on my page it won't show

281