How to limit the number of characters entered in a field?

Some sites have a limit on the number of characters entered in a field (for example, leaving a comment), after typing the maximum number of characters, nothing is entered further, how to make this limit?


Answer 1, authority 100%

If the field is input type=text, then maxlengthis set; if textareathen javascript is needed). And even then all this can be bypassed) In PHP, you can check the length of the entered data through strlenand if it is more than – return an error)
So what do you want an example of? html, javascript, php??


Answer 2, authority 50%

Here is for all browsers that support paste,

$('.limited').bind('keyup keydown paste',function(e) {
    var $t=$(this);
    setTimeout(function(){ 
    var max=$t.attr('maxlength')*1;
    if ($t.val().length>max) {
        $t.val($t.val().substr(0,max));
    }
    $t.next().children('span').text(max-$t.val().length);
    },0);
});

setTimeoutis necessary for the string to get into the field, and then you can work with it.

demo