最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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');
    });

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');
    });
Share Improve this question asked Nov 12, 2015 at 5:07 gotsamegotsame 431 silver badge4 bronze badges 1
  • 1 set the count value in a cookie – coolguy Commented Nov 12, 2015 at 5:09
Add a ment  | 

5 Answers 5

Reset to default 4

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.

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 ment = $('#description');
    var val = localStorage.getItem( ment.attr('id') ),
        max = 4000,
        len = val.length,
        left = ( max - len ) ;
    // if the value exists, set it
    if (val) {
        ment.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

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./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.

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.

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论