web-dev-qa-db-fra.com

Comment imposer maxlength à textArea en HTML à l'aide de JavaScript

J'aimerais avoir une fonctionnalité par laquelle si j'écris

<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>

il imposera automatiquement la longueur maximale à la zone de texte. Si possible, veuillez ne pas fournir la solution dans jQuery.

Note: Ceci peut être fait si je fais quelque chose comme ceci:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">

function imposeMaxLength(Event, Object, MaxLen)
{
    return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}

Copié à partir de Quel est le meilleur moyen d'émuler un attribut HTML “maxlength” sur une zone de texte HTML?

Mais le fait est que je ne veux pas écrire onKeyPress et onKeyUp chaque fois que je déclare un textArea.

115
Rakesh Juyal
window.onload = function() { 
  var txts = document.getElementsByTagName('TEXTAREA'); 

  for(var i = 0, l = txts.length; i < l; i++) {
    if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { 
      var func = function() { 
        var len = parseInt(this.getAttribute("maxlength"), 10); 

        if(this.value.length > len) { 
          alert('Maximum length exceeded: ' + len); 
          this.value = this.value.substr(0, len); 
          return false; 
        } 
      }

      txts[i].onkeyup = func;
      txts[i].onblur = func;
    } 
  };

}
111
Josh Stodola

Je sais que vous voulez éviter jQuery, mais comme la solution nécessite JavaScript, cette solution (utilisant jQuery 1.4) est la plus cohérente et la plus robuste.

Inspiré par, mais une amélioration par rapport à la réponse de Dana Woodman:

Les modifications apportées à cette réponse sont les suivantes: simplifiée et plus générique, utilisation de jQuery.live et non non définition de val si longueur est correcte (conduit à utiliser les touches fléchées dans IE et une accélération notable dans IE):

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

EDIT: Version mise à jour pour jQuery 1.7 + , en utilisant on au lieu de live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});
80
Eirik W

Mise à jour Utilisez la solution Eirik en utilisant .live() à la place car elle est un peu plus robuste.


Même si vous vouliez une solution qui n'utilisait pas jQuery, j'ai pensé en ajouter une pour tous ceux qui trouveraient cette page via Google et rechercheraient une solution jQuery-esque:

$(function() {        
    // Get all textareas that have a "maxlength" property.
    $('textarea[maxlength]').each(function() {

        // Store the jQuery object to be more efficient...
        var $textarea = $(this);

        // Store the maxlength and value of the field.
        var maxlength = $textarea.attr('maxlength');
        var val = $textarea.val();

        // Trim the field if it has content over the maxlength.
        $textarea.val(val.slice(0, maxlength));

        // Bind the trimming behavior to the "keyup" event.
        $textarea.bind('keyup', function() {
            $textarea.val($textarea.val().slice(0, maxlength));
        });

    });
});

J'espère que cela vous sera utile. Googlers ...

33
Dana Woodman

HTML5 ajoute un attribut maxlength à l'élément textarea, comme suit:

<!DOCTYPE html>
<html>
    <body>
        <form action="processForm.php" action="post">
            <label for="story">Tell me your story:</label><br>
            <textarea id="story" maxlength="100"></textarea>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

Ceci est actuellement pris en charge dans Chrome 13, FF 5 et Safari 5. Evidemment, cela n’est pas pris en charge dans IE 9. (testé sous Windows 7)

31
james.garriss

Cette solution évite le problème dans IE où le dernier caractère est supprimé lors de l'ajout d'un caractère au milieu du texte. Cela fonctionne aussi très bien avec les autres navigateurs.

$("textarea[maxlength]").keydown( function(e) {
    var key = e.which;  // backspace = 8, delete = 46, arrows = 37,38,39,40

    if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;

    return $(this).val().length < $(this).attr( "maxlength" );
});

La validation de mon formulaire traite ensuite de tous les problèmes pour lesquels l'utilisateur a peut-être collé (cela ne semble être un problème que dans IE) du texte dépassant la longueur maximale de la zone de texte.

5
Chris R

Ceci est un code modifié que je viens d'utiliser sur mon site. Il est amélioré d'afficher le nombre de caractères restants à l'utilisateur.

(Désolé encore pour OP qui n'a pas demandé jQuery. Mais sérieusement, qui n'utilise pas jQuery ces jours-ci?)

$(function() {
    // Get all textareas that have a "maxlength" property.
    $("textarea[maxlength]").each(function() {

        // Store the jQuery object to be more efficient...
        var $textarea = $(this);

        // Store the maxlength and value of the field
        var maxlength = $textarea.attr("maxlength");

        // Add a DIV to display remaining characters to user
        $textarea.after($("<div>").addClass("charsRemaining"));

        // Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
        $textarea.on("keyup blur", function(event) {
            // Fix OS-specific line-returns to do an accurate count
            var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
            $textarea.val(val);
            // Display updated count to user
            $textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
        }).trigger("blur");

    });
});

N'a PAS été testé avec des caractères internationaux multi-octets, je ne suis donc pas sûr de savoir comment cela fonctionne avec ceux-ci exactement.

3
Simon East

L'attribut maxlength est pris en charge dans Internet Explorer 10, Firefox, Chrome et Safari.

Remarque: L'attribut maxlength de la balise <textarea> n'est pas pris en charge dans Internet Explorer 9 et les versions antérieures, ni dans Opera.

à partir de HTML maxlength Attribute w3schools.com

Pour IE8 ou les versions antérieures, vous devez utiliser les éléments suivants

//only call this function in IE
function maxLengthLimit($textarea){
    var maxlength = parseInt($textarea.attr("maxlength"));
    //in IE7,maxlength attribute can't be got,I don't know why...
    if($.browser.version=="7.0"){
        maxlength = parseInt($textarea.attr("length"));
    }
    $textarea.bind("keyup blur",function(){
        if(this.value.length>maxlength){
            this.value=this.value.substr(0,maxlength);
        }
    });
}

P.S.

L'attribut maxlength de la balise <input> est pris en charge par tous les principaux navigateurs.

à partir de HTML maxlength Attribute w3schools.com

2
Eason

Ajoutez également l'événement suivant pour traiter le collage dans la zone de texte:

...

txts[i].onkeyup = function() {
  ...
}

txts[i].paste = function() {
  var len = parseInt(this.getAttribute("maxlength"), 10);

  if (this.value.length + window.clipboardData.getData("Text").length > len) {
    alert('Maximum length exceeded: ' + len);
    this.value = this.value.substr(0, len);
    return false;
  }
}

...
2
stusherwin

Vous pouvez utiliser jQuery pour le rendre facile et clair

JSFiddle DÉMO

<textarea id="ta" max="10"></textarea>

<script>
$("#ta").keypress(function(e){

    var k = e.which==0 ? e.keyCode : e.which;
    //alert(k);
    if(k==8 || k==37 || k==39 || k==46) return true;

    var text      = $(this).val();
    var maxlength = $(this).attr("max");

    if(text.length >= maxlength) {
        return false;   
    }
    return true;
});
</script>

Il est testé dans Firefox, Google Chrome et Opera

1
Salim

Meilleure solution par rapport à la réduction de la valeur de la zone de texte.

$('textarea[maxlength]').live('keypress', function(e) {
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    if (val.length > maxlength) {
        return false;
    }
});
1
Bharat

J'ai récemment implémenté le comportement maxlength sur textarea et je rencontre le problème décrit dans cette question: Chrome compte les caractères incorrects dans textarea avec l'attribut maxlength .

Donc, toutes les implémentations listées ici fonctionneront sans problème. Pour résoudre ce problème, j'ajoute .replace(/(\r\n|\n|\r)/g, "11") avant .length. Et gardez cela à l’esprit lorsque vous coupez du fil.

J'ai fini avec quelque chose comme ça:

var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
    el.val(val.slice(0, maxlength - (realLength - length)));
}

Je ne sais pas si cela résout complètement le problème, mais cela fonctionne pour moi pour le moment.

0
Roman Pominov

Essayez d'utiliser cet exemple de code:

$("#TextAreaID1").bind('input propertychange', function () {
    var maxLength = 4000;
    if ($(this).val().length > maxLength) {
        $(this).val($(this).val().substring(0, maxLength));
    }
});
0
naveen

Essayez cette jQuery qui fonctionne dans IE9, FF, Chrome et fournit un compte à rebours aux utilisateurs:

$("#comments").bind("keyup keydown", function() {
    var max = 500;
    var value = $(this).val();
    var left = max - value.length;
    if(left < 0) {
        $(this).val( value.slice(0, left) );
        left = 0;
    }
    $("#charcount").text(left);
}); 

<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>
0
Leslie King

Le petit problème avec le code ci-dessus est que val () ne déclenche pas l'événement change (). Par conséquent, si vous utilisez backbone.js (ou un autre framework pour la liaison de modèle), le modèle ne sera pas mis à jour.

Je poste la solution qui a très bien fonctionné pour moi.

$(function () {

    $(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
        var maxLength = $(this).attr('maxlength');
        if (e.keyCode > 47 && $(this).val().length >= maxLength) {
            $(this).val($(this).val().substring(0, maxLength)).trigger('change');
        }
        return true;
    });

});
0
Alexander Beletsky