2010-05-10 24 views
5

Aquí está mi intento de limitar el número de caracteres introducidos en un área de texto:Cómo limitar el número de caracteres introducidos en un área de texto

var limit = 255; 
var txt = $('textarea[id$=txtPurpose]'); 

$(txt).keyup(function() { 
    var len = $(this).val().length; 
    if (len > limit) { 
     //this.value = this.value.substring(0, 50); 
     $(this).addClass('goRed'); 
     $('#spn').text(len - limit + " characters exceeded"); 
     return false; 
    } else { 
     $(this).removeClass('goRed'); 
     $('#spn').text(limit - len + " characters left"); 
    } 
}); 

Sin embargo, no funciona muy bien. ¿Cómo puedo evitar que un usuario ingrese texto una vez que se ha alcanzado un cierto límite, digamos 255 caracteres?

Respuesta

9

Esto es lo que uso para limitar algo a 1200 caracteres. Cuando alguien escribe demasiados caracteres, trunco ​​el contenido de ese área de texto.

$(function() { 
    //set up text length counter 
    $('#id_limited_textarea').keyup(function() { 
     update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left')); 
    }); 
    //and fire it on doc ready, too 
    update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left')); 

}); 

function update_chars_left(max_len, target_input, display_element) { 
    var text_len = target_input.value.length; 
    if (text_len >= max_len) { 
     target_input.value = target_input.value.substring(0, max_len); // truncate 
     display_element.html("0"); 
    } else { 
     display_element.html(max_len - text_len); 
    } 
} 
+0

Ha copiado y pegado la llamada update_chars_left(), aunque los parámetros son los mismos. – mikemaccana

+0

Esto se puede simplificar aún más, consulte mi respuesta a continuación. –

5
$(this).val($(this).val().substring(0, limit)); 
+0

no está truncando los caracteres. –

+0

@Abu: Vaya, prueba esto –

+1

¿Este código está mejor ubicado dentro del evento de teclado? –

1

Mi plugin:

(function($) { 

    $.fn.textCounter = function(options) { 

     var defaults = { 
      maxlimit: 100,  // max limit character 
      description: null, // element for descript count character 
      enter: true   // if accept enter 
     }; 

     var options = $.extend({}, defaults, options); 

     if (options.description != null) { 
      if (typeof options.description == 'string') 
       options.description = $('#' + options.description); 
     } 

     var fevent = function(ev) { 

      var value = $(this).val(), 
       k = ev.charCode || ev.keyCode || ev.which, 
       incremente = 1; 

      if (k == 8) 
       incremente = -1; 

      if (options.enter == false && k == 13) 
       return false; 

      if (ev.ctrlKey || ev.altKey || ev.metaKey) //Ignore 
       return true; 

      if ((value.length + incremente) > options.maxlimit) 
       return false; 

      return true; 
     }; 

     var fcounter = function(ev) { 
      var value = $(this).val(); 
      $(options.description).text(options.maxlimit - value.length); 
     }; 

     $(this).each(function(i, el) { 
      if ($(this).is(':input')) { 
       $(this).unbind('keypress.textCounter').bind('keypress.textCounter', fevent); 
       $(this).unbind('keyup.textCounter').bind('keyup.textCounter', fcounter); 
      } 
     }); 

    }; 

})(jQuery); 
0
var limit="NO of characters";<br><br> 
$(this).val($(this).val().substring(0, limit)); 
9

Aunque esta pregunta es bastante viejo. Si yo fuera tú hago algo muy simple como

<textarea maxlength="255"></textarea> 

Esto limitaría los usuarios entrar en sólo 255 caracteres en el área de texto.

+1

gracias amigo ... me olvidé de eso :) - una solución de 0.0001kb (+1) –

+0

¿Cuál es el soporte para 'maxlength'? –

3

Para simplificar esto con el hueso desnudo básica:

<textarea name="message" onkeydown="return this.value.substr(0,160)"></textarea> 

Indica tu máximo a 160, donde es.

Cuestiones relacionadas