type minlength characters and html input textarea

characters - minlength maxlength html input



Establecer maxlength en Html Textarea (9)

Esta pregunta ya tiene una respuesta aquí:

¿Cómo puedo establecer el maxlength en un área de textarea ? ¿Y por qué maxlength no funciona correctamente en textarea ?


Antes de HTML5 solo es posible verificar esto con JavaScript o mediante una verificación del lado del servidor (mejor, porque JavaScript obviamente solo funciona con JavaScript habilitado ...). No existe un atributo nativo de longitud máxima para textareas.

Desde HTML5, es un atributo válido, por lo que la definición de su doctype como HTML5 puede ayudar. Sin embargo, no sé si todos los navegadores admiten este atributo:

<!DOCTYPE html>


Antes de HTML5, tenemos una manera fácil pero viable: primero establecer un atributo maxlength en el elemento textarea:

<textarea maxlength=''250'' name=''''></textarea>

Luego use JavaScript para limitar la entrada del usuario:

$(function() { $("textarea[maxlength]").bind(''input propertychange'', function() { var maxLength = $(this).attr(''maxlength''); if ($(this).val().length > maxLength) { $(this).val($(this).val().substring(0, maxLength)); } }) });

Asegúrese de enlazar los eventos de " entrada " y "cambio de propiedad " para que funcione en varios navegadores como Firefox / Safari e IE.


Como dije en un comentario a la respuesta de aqingsao, no funciona cuando el área de textarea tiene caracteres de nueva línea, al menos en Windows.

He cambiado su respuesta un poco así:

$(function() { $("textarea[maxlength]").bind(''input propertychange'', function() { var maxLength = $(this).attr(''maxlength''); //I''m guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error. //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input. var newlines = ($(this).val().match(//n/g) || []).length if ($(this).val().length + newlines > maxLength) { $(this).val($(this).val().substring(0, maxLength - newlines)); } }) });

Ahora, cuando intento pegar muchos datos con líneas nuevas, obtengo exactamente el número correcto de caracteres.


La forma simple de hacer maxlength para textarea en html4 es:

<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>

Cambia el "100" a cuantos personajes quieras


Si está utilizando HTML 5, debe especificarlo en su declaración DOCTYPE .

Para un documento HTML 5 válido, debería comenzar con:

<!DOCTYPE html>

Antes de HTML 5, el elemento textarea no tenía un atributo maxlength .

Puedes ver esto en la DTD/spec :

<!ELEMENT TEXTAREA - - (#PCDATA) -- multi-line text field --> <!ATTLIST TEXTAREA %attrs; -- %coreattrs, %i18n, %events -- name CDATA #IMPLIED rows NUMBER #REQUIRED cols NUMBER #REQUIRED disabled (disabled) #IMPLIED -- unavailable in this context -- readonly (readonly) #IMPLIED tabindex NUMBER #IMPLIED -- position in tabbing order -- accesskey %Character; #IMPLIED -- accessibility key character -- onfocus %Script; #IMPLIED -- the element got the focus -- onblur %Script; #IMPLIED -- the element lost the focus -- onselect %Script; #IMPLIED -- some text was selected -- onchange %Script; #IMPLIED -- the element value was changed -- %reserved; -- reserved for possible future use -- >

Para limitar el número de caracteres escritos en un área de textarea , deberá usar javascript con el evento onChange . Luego puede contar la cantidad de caracteres y no permitir escribir más.

Here hay una discusión en profundidad sobre el ingreso de texto y cómo usar el servidor y las secuencias de comandos del lado del cliente para limitar el tamaño.

Here hay otra muestra.


cambiar el tamaño: ninguno; Esta propiedad arregla tu área de texto y la enlaza. usted usa esta identificación de propiedad css su área de texto textarea.gave y una identificación y en nombre de esa identificación puede usar esta propiedad css.


prueba esto

$(function(){ $("textarea[maxlength]") .keydown(function(event){ return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46; }) .keyup(function(event){ var limit = $(this).attr("maxlength"); if (!limit) return; if (this.value.length <= limit) return true; else { this.value = this.value.substr(0,limit); return false; } }); });

Para mí funciona realmente perfecto sin saltar / mostrar caracteres adicionales; funciona exactamente como maxlength en la entrada


$(function(){ $("#id").keypress(function() { var maxlen = 100; if ($(this).val().length > maxlen) { return false; } }) });


<p> <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> </p> <p id="valmess2" style="color:red" ></p> function cnt(event) { document.getElementById("valmess2").innerHTML=""; // init and clear if b < max allowed character a = document.getElementById("msgc").value; b = a.length; if (b > 400) { document.getElementById("valmess2").innerHTML="the max length of 400 characters is reached, you typed in " + b + "characters"; } }

maxlength solo es válido para HTML5. Para HTML / XHTML debes usar JavaScript y / o PHP. Con PHP puede usar strlen por ejemplo. Este ejemplo indica solo la longitud máxima, NO está bloqueando la entrada.