Basit
Basit

Reputation: 8606

How to prevent user to enter text in textarea after reaching max character limit

I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code.

jQuery(document).ready(function($) {
    $('textarea.max').keyup(function() {
        var $textarea = $(this);
        var max = 400;
        if ($textarea.val().length > max) {
            var top = $textarea.scrollTop();
            $textarea.val($textarea.val().substr(0, max));
            $textarea.scrollTop(top);

        }
    });
}); //end if ready(fn)

But i also want that after reaching max limit user unable to type anything in the textarea. Currently what happen that after reaching max limit if user press and hold the key, the characters are typing in the text area, although after releasing the button it come back to original text (i.e $textarea.val($textarea.val().substr(0, max)); ). But i want that once this condition become true

if ($textarea.val().length > max) {

user unable to type anything. I want that cursor vanishes from the textarea. But if user remove some text then cursor also available for user to type input again. How can I do it?

Upvotes: 30

Views: 97180

Answers (9)

Shanish Singh
Shanish Singh

Reputation: 1

 <script type="text/javascript">
        $(document).ready(function () {
            maxlength("TextArea1");
        });
        function maxlength(id) {
            $('#' + id).on('input propertychange', function () {
                CharLimit(this, 20);
            });
        }

        function CharLimit(input, maxChar) {
            var len = $(input).val().length;
            if (len > maxChar) {
                $(input).val($(input).val().substring(0, maxChar));
            }
        }
 </script>

Upvotes: -1

arb
arb

Reputation: 7863

You could use this plugin instead of trying to write your own. I've found that it works pretty well.

Upvotes: 0

Gus
Gus

Reputation: 7525

For those already using ES2015 in your browsers, here's an implementation using some of the answers above:

class InputCharacterCount {
  constructor(element, min, max) {
    this.element = element;
    this.min = min;
    this.max = max;
    this.appendCharacterCount();
  }

  appendCharacterCount(){
    let charCount = `<small class="char-counter help-block"></small>`;
    this.element.closest('.form-group').append(charCount);
  }

  count(event){
    this.element.attr('maxlength', this.max); // Add maxlenght attr to input element

    let value = this.element.val();
    this.element
      .closest('.form-group')
      .find('.char-counter')
      .html(value.length+'/'+this.max); // Add a character count on keyup/keypress

    if (value.length < this.min || value.length > this.max) { // color text on min/max changes
      this.element.addClass('text-danger');
    } else {
      this.element.removeClass('text-danger');
    }
  }
}

Usage:

let comment = $('[name="collection-state-comment"]');
let counter = new InputCharacterCount(comment, 21, 140);
$(comment).keyup(function(event){
  counter.count(event);
});

Upvotes: 0

GuRu
GuRu

Reputation: 1886

You could directly give maxlength to textarea to disable itself. But, you want to showing appropriate message then use keyup event for default behavior and textarea length for calculating charcter and display suitable message.

HTML

<div id="count"></div>
<textarea class="max"  maxlength="250" id="tarea"></textarea>
<div id="msg"></div>

jQuery

$(function(){
    var max = parseInt($("#tarea").attr("maxlength"));
  $("#count").text("Characters left: " + max);
    $("#tarea").keyup(function(e){
        $("#count").text("Characters left: " + (max - $(this).val().length));
    if($(this).val().length==max)
        $("#msg").text("Limit Reached....");
        else
        $("#msg").text("");
    });
});

Demo Fiddle

Upvotes: 1

ProllyGeek
ProllyGeek

Reputation: 15836

You can keep your event as they are , and just use this library

Examples

// applying a click event to one element

Touche(document.querySelector('#myButton')).on('click', handleClick);

// or to multiple at once

Touche(document.querySelectorAll('.myButtons')).on('click', handleClicks);

// or with jQuery

$('.myButtons').on('click', handleClicks);

Upvotes: 0

Joseph Fizzy Beats
Joseph Fizzy Beats

Reputation: 49

Keep it simple

var max = 50;
$("#textarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
});

and add this in your html

<textarea id="textarea" maxlength="50"></textarea>
<div id="count"></div>

view example

Upvotes: 4

ViPuL5
ViPuL5

Reputation: 613

Just write this code in your Javascript file.. But Need to specify the 'maxlength' attribute with textarea. This will work for all textarea of a page.

$('textarea').bind("change keyup input",function() {

        var limitNum=$(this).attr("maxlength");

        if ($(this).val().length > limitNum) {
            $(this).val($(this).val().substring(0, limitNum));
        }

    });

Upvotes: 2

Rob W
Rob W

Reputation: 349012

The keyup event fires after the default behaviour (populating text area) has occurred.

It's better to use the keypress event, and filter non-printable characters.

Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)

jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)

Upvotes: 58

KBN
KBN

Reputation: 2974

<textarea maxlength="400"> </textarea>

Use the above code to limit the number of characters inserted in a text area, if you want to disable the textarea itself (ie, will not be able to edit afterwards) you can use javascript/jquery to disable it.

Upvotes: 35

Related Questions