Contar caracteres en el área de texto


Quiero contar caracteres en un área de texto, así que acabo de hacer:

<textarea id="field" onkeyup="countChar(this)"></textarea>

function countChar(val){
     var len = val.value.length;
     if (len >= 500) {
              val.value = val.value.substring(0, 500);
     } else {
              $('#charNum').text(500 - len);
     }
};

¿Qué tiene de malo mi fragmento de código? No funciona! Bueno, esa fue una letra de novato, necesito ayuda.

Author: Filburt, 2011-03-20

21 answers

¿Qué errores está viendo en el navegador? Puedo entender por qué su código no funciona si lo que publicó estaba incompleto, pero sin saber que no puedo estar seguro.

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>
      function countChar(val) {
        var len = val.value.length;
        if (len >= 500) {
          val.value = val.value.substring(0, 500);
        } else {
          $('#charNum').text(500 - len);
        }
      };
    </script>
  </head>

  <body>
    <textarea id="field" onkeyup="countChar(this)"></textarea>
    <div id="charNum"></div>
  </body>

</html>

... funciona bien para mí.

Editar: Probablemente deberías borrar el div de charNum, o escribir algo, si están por encima del límite.

 149
Author: Caterham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 19:36:26

Versión mejorada basada en la función de Caterham :

$('#field').keyup(function () {
  var max = 500;
  var len = $(this).val().length;
  if (len >= max) {
    $('#charNum').text(' you have reached the limit');
  } else {
    var char = max - len;
    $('#charNum').text(char + ' characters left');
  }
});
 79
Author: keithics,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:31

}️ La solución aceptada es defectuosa.

Aquí hay dos escenarios donde el evento keyup no se disparará:

  1. El usuario arrastra texto dentro del área de texto.
  2. El usuario copia y pega el texto en el área de texto con un clic derecho (menú contextual).

Use el evento HTML5 input en su lugar para una solución más robusta:

<textarea maxlength='140'></textarea>

JavaScript (demo):

var textarea = document.querySelector("textarea");

textarea.addEventListener("input", function(){
    var maxlength = this.getAttribute("maxlength");
    var currentLength = this.value.length;

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
    }else{
        console.log(maxlength - currentLength + " chars left");
    }
});

Y si quieres usar jQuery:

$('textarea').on("input", function(){
    var maxlength = $(this).attr("maxlength");
    var currentLength = $(this).val().length;

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
    }else{
        console.log(maxlength - currentLength + " chars left");
    }
});
 40
Author: Etienne Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 14:49:48

Esto funcionó bien para mí.

$('#customText').on('keyup', function(event) {
   var len = $(this).val().length;
   if (len >= 40) {
      $(this).val($(this).val().substring(0, len-1));
   }
});
 8
Author: fatsouls32,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-31 23:57:53

Muestra HTML, utilizada donde sea que necesite un contador, observe la relevancia de los ID de textarea y second span : id="post" id="rem_post" y el título del lapso que contiene la cantidad de caracteres deseada de cada área de texto en particular

<textarea class="countit" name="post" id="post"></textarea>
<p>
  <span>characters remaining: <span id="rem_post" title="1000"></span></span>
</p>

La función JavaScript, normalmente colocada antes de </body> en mi archivo de plantilla, requiere jQuery

$(".countit").keyup(function () {
  var cmax = $("#rem_" + $(this).attr("id")).attr("title");

  if ($(this).val().length >= cmax) {
    $(this).val($(this).val().substr(0, cmax));
  }

  $("#rem_" + $(this).attr("id")).text(cmax - $(this).val().length);

});
 7
Author: humugus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 19:41:57

substring() necesita convertirse en substr().

Ejemplo: jsfiddle.net/xqyWV

 6
Author: mattsven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-21 22:35:13

Bueno, esto no es tan diferente de lo que se ha dicho, pero esto funciona muy bien en todos los navegadores.

La idea es eliminar cualquier texto que rebase la longitud definida.

function countTextAreaChar(txtarea, l){
    var len = $(txtarea).val().length;
    if (len > l) $(txtarea).val($(txtarea).val().slice(0, l));
    else $('#charNum').text(l - len);
    }

El código HTMl sería:

<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>
 4
Author: josemaria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 15:49:27

HTML

<form method="post">
<textarea name="postes" id="textAreaPost" placeholder="Write what's you new" maxlength="500"></textarea>

<div id="char_namb" style="padding: 4px; float: right; font-size: 20px; font-family: Cocon; text-align: center;">500 : 0</div>
</form>
[2]} jQuery
$(function(){
    $('#textAreaPost').keyup(function(){
      var charsno = $(this).val().length;
      $('#char_namb').html("500 : " + charsno);
    });
});
 4
Author: Elkingphp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-13 16:35:19

Hice una combinación de lo anterior. Permite la detención de la entrada de texto, y permite el backspacing, además mantiene la cuenta, incluso cuando backspacing:

Código JavaScript:

$(document).ready(function () {

  $('#giftmsg').keypress(function (event) {
    var max = 250;
    var len = $(this).val().length;

    if (event.which < 0x20) {
      // e.which < 0x20, then it's not a printable character
      // e.which === 0 - Not a character
      return; // Do nothing
    }

    if (len >= max) {
      event.preventDefault();
    }

  });

  $('#giftmsg').keyup(function (event) {
    var max = 250;
    var len = $(this).val().length;
    var char = max - len;

    $('#textleft').text(char + ' characters left');

  });

});

HTML:

<div class="col3">
    <h2>3. Optional gift message</h2>
    Enter gift message. Limit 250 characters.<br /><br />
    <textarea cols="36" rows="5" id="giftmsg" ></textarea>
    <a style="padding:7px 0 0 0" href="#">Save Message</a>
    <div id="textleft">250 characters left</div>
</div>

Crédito a los carteles antes de mí!! Espero que esto ayude a alguien!

 3
Author: DJH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-12 19:44:05

He creado mi propio plugin jQuery para esta tarea, puedes probarlo aquí:

Http://jsfiddle.net/Sk8erPeter/8NF4r /

Puede crear contadores de caracteres sobre la marcha (y también contadores de caracteres restantes), puede definir si desea cortar texto, puede definir los textos de sufijos y también puede definir un formato corto y su separador.

Aquí hay un ejemplo de uso:

$(document).ready(function () {

    $('#first_textfield').characterCounter();

    $('#second_textfield').characterCounter({
        maximumCharacters: 20,
        chopText: true
    });

    $('#third_textfield').characterCounter({
        maximumCharacters: 20,
        shortFormat: true,
        shortFormatSeparator: " / ",
        positionBefore: true,
        chopText: true
    });

    $('#fourth_textfield').characterCounter({
        maximumCharacters: 20,
        characterCounterNeeded: true,
        charactersRemainingNeeded: true,
        chopText: false
    });

    $('#first_textarea').characterCounter({
        maximumCharacters: 50,
        characterCounterNeeded: true,
        charactersRemainingNeeded: false,
        chopText: true
    });

    $('#second_textarea').characterCounter({
        maximumCharacters: 25
    });

});

Aquí está el código del plugin:

/**
 * Character counter and limiter plugin for textfield and textarea form elements
 * @author Sk8erPeter
 */ 
(function ($) {
  $.fn.characterCounter = function (params) {
    // merge default and user parameters
    params = $.extend({
      // define maximum characters
      maximumCharacters: 1000,
      // create typed character counter DOM element on the fly
      characterCounterNeeded: true,
      // create remaining character counter DOM element on the fly
      charactersRemainingNeeded: true,
      // chop text to the maximum characters
      chopText: false,
      // place character counter before input or textarea element
      positionBefore: false,
      // class for limit excess
      limitExceededClass: "character-counter-limit-exceeded",
      // suffix text for typed characters
      charactersTypedSuffix: " characters typed",
      // suffix text for remaining characters
      charactersRemainingSuffixText: " characters left",
      // whether to use the short format (e.g. 123/1000)
      shortFormat: false,
      // separator for the short format
      shortFormatSeparator: "/"
    }, params);

    // traverse all nodes
    this.each(function () {
      var $this = $(this),
        $pluginElementsWrapper,
        $characterCounterSpan,
        $charactersRemainingSpan;

      // return if the given element is not a textfield or textarea
      if (!$this.is("input[type=text]") && !$this.is("textarea")) {
        return this;
      }

      // create main parent div
      if (params.characterCounterNeeded || params.charactersRemainingNeeded) {
        // create the character counter element wrapper
        $pluginElementsWrapper = $('<div>', {
          'class': 'character-counter-main-wrapper'
        });

        if (params.positionBefore) {
          $pluginElementsWrapper.insertBefore($this);
        } else {
          $pluginElementsWrapper.insertAfter($this);
        }
      }

      if (params.characterCounterNeeded) {
        $characterCounterSpan = $('<span>', {
          'class': 'counter character-counter',
          'text': 0
        });

        if (params.shortFormat) {
          $characterCounterSpan.appendTo($pluginElementsWrapper);

          var $shortFormatSeparatorSpan = $('<span>', {
            'html': params.shortFormatSeparator
          }).appendTo($pluginElementsWrapper);

        } else {
          // create the character counter element wrapper
          var $characterCounterWrapper = $('<div>', {
            'class': 'character-counter-wrapper',
            'html': params.charactersTypedSuffix
          });

          $characterCounterWrapper.prepend($characterCounterSpan);
          $characterCounterWrapper.appendTo($pluginElementsWrapper);
        }
      }

      if (params.charactersRemainingNeeded) {

        $charactersRemainingSpan = $('<span>', {
          'class': 'counter characters-remaining',
          'text': params.maximumCharacters
        });

        if (params.shortFormat) {
          $charactersRemainingSpan.appendTo($pluginElementsWrapper);
        } else {
          // create the character counter element wrapper
          var $charactersRemainingWrapper = $('<div>', {
            'class': 'characters-remaining-wrapper',
            'html': params.charactersRemainingSuffixText
          });
          $charactersRemainingWrapper.prepend($charactersRemainingSpan);
          $charactersRemainingWrapper.appendTo($pluginElementsWrapper);
        }
      }

      $this.keyup(function () {

        var typedText = $this.val();
        var textLength = typedText.length;
        var charactersRemaining = params.maximumCharacters - textLength;

        // chop the text to the desired length
        if (charactersRemaining < 0 && params.chopText) {
          $this.val(typedText.substr(0, params.maximumCharacters));
          charactersRemaining = 0;
          textLength = params.maximumCharacters;
        }

        if (params.characterCounterNeeded) {
          $characterCounterSpan.text(textLength);
        }

        if (params.charactersRemainingNeeded) {
          $charactersRemainingSpan.text(charactersRemaining);

          if (charactersRemaining <= 0) {
            if (!$charactersRemainingSpan.hasClass(params.limitExceededClass)) {
              $charactersRemainingSpan.addClass(params.limitExceededClass);
            }
          } else {
            $charactersRemainingSpan.removeClass(params.limitExceededClass);
          }
        }
      });

    });

    // allow jQuery chaining
    return this;

  };
})(jQuery);
 3
Author: Sk8erPeter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-09 15:19:07
$.fn.extend( {
       limiter: function(limit, elem) {
            $(this).on("keyup focus", function() {
               setCount(this, elem);
           });
            function setCount(src, elem) {
               var chars = src.value.length;
                if (chars > limit) {
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                }
                elem.html( limit - chars );
            }
            setCount($(this)[0], elem);
        }
    });

    var elem = $("#cntr");  
    $("#status_txt").limiter(160, elem);
 2
Author: Saurabh Chandra Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-30 08:30:03

Me preguntaba cómo hacer esto mismo y tomando ideas de todos aquí esto es lo que se me ocurrió:

JsFiddle

<textarea name="message" rows="4" cols="24" maxlength="1000" id="message" placeholder="Message:" style=""></textarea><br/>
<span id="charNum"></span>

$('#message').keyup(function () {
  max = this.getAttribute("maxlength");
  var len = $(this).val().length;
   if (len >= max) {
    $('#charNum').text(' you have reached the limit');
   } else {
    var char = max - len;
    $('#charNum').text(char + ' characters left');
   }
});
 1
Author: bckelley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-03 00:27:45

Su código estaba un poco confundido. Aquí hay una versión limpia:

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
            $.post("SetAndGet.php", {
                know: $("#know").val()
            }, function(data) {
                $("#know_list").html(data);
            });
        });

        function countChar(val) {
            var len = val.value.length;
            if (len >= 500) {
                val.value = val.value.substring(0, 500);
            } else {
                $('#charNum').text(500 - len);
            }
        }
    });
</script>
 0
Author: Sylvain Guillopé,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-20 20:37:48

Prueba este.

<textarea maxlength="410" name="about_me" onkeydown="CountLeft(this.form.about_me, this.form.left);" onkeyup="CountLeft(this.form.about_me,this.form.left); "></textarea>

<input maxlength="3" name="left" readonly="" size="3" type="text" value="410" /> characters left

<script>
function CountLeft(field, count) 
{
    var max = "410";
    if (field.value.length > max)
    {
        field.value = field.value.substring(0, max);
    }
    else
    {
        count.value = max - field.value.length;
    }
}
</script>
 0
Author: Hardik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-11 15:02:23

Una versión más genérica para que pueda usar la función para más de un campo.

<script src="../site/jquery/jquery.min.js" ></script>
<script type="text/javascript">

function countChar(inobj, maxl, outobj) {
    var len = inobj.value.length;
    var msg = ' chr left';
    if (len >= maxl) {
        inobj.value = inobj.value.substring(0, maxl);
        $(outobj).text(0 + msg);
    } else {
        $(outobj).text(maxl - len + msg);
    }
}


$(document).ready(function(){

    //set up summary field character count
    countChar($('#summary').get(0),500, '#summarychrs'); //show inital value on page load
    $('#summary').keyup(function() {
        countChar(this, 500, '#summarychrs'); //set up on keyup event function
    });

});
</script>

<textarea name="summary" id="summary" cols="60" rows="3" ><?php echo $summary ?></textarea> 
<span id="summarychrs">0</span>
 0
Author: Lumis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-20 03:42:12
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

    <script>

            function countChar(val) 
            {

             var limit = 1024;

            if ( val.length > limit )
              { 
              $("#comment").val(val.substring(0, limit-1));
              val.length = limit;
              }

              $("#count").html((limit)-(val.length));     
              }

        </script>

        <textarea id="comment" onKeyUp="countChar(this.value)" required></textarea>

        <div id="count"></div>

Use lo siguiente para omitir el uso de else y también omitir obtener conteo negativo.

 0
Author: Shiva Charan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-20 14:39:42

Aquí mi ejemplo. Cena simple

$(document).ready(function() {
      
        var textarea    = $("#my_textarea");
  
        textarea.keydown(function(event) {
          
            var numbOfchars = textarea.val();
            var len = numbOfchars.length;
            $(".chars-counter").text(len);

        });
  
  
 }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="my_textarea" class="uk-textarea" rows="5" name="text"></textarea>
<h1 class="chars-counter">0</h1>
 0
Author: Ivan Milincic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 14:00:15

No estábamos contentos con ninguna de las soluciones propuestas.

Así que hemos creado una solución completa de contador de caracteres para jQuery, construida sobre jquery-jeditable. Es una extensión de complemento textarea que puede contar en ambos sentidos, muestra un mensaje personalizado, limita el recuento de caracteres y también admite jquery-datatables.

Puede probarlo de inmediato en JSFiddle.

Enlace de GitHub: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount

Inicio rápido

Añade estas líneas a tu HTML:

<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.jeditable.charcounter.realworld.min.js"></script>
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.charcounter.realworld.min.js"></script>

Y luego:

$("#myTextArea4").charCounter();
 0
Author: Vaiden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-07 06:04:08
$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Además, puede poner su propio id de elemento o clase en lugar de " h1 " y contar el evento de longitud de sus caracteres de cadena de área de texto {

 0
Author: parham rahimpour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-07 07:28:25
$('#field').keyup(function () {
    var max = 160;
    var len = $(this).val().length;
//  var char = max - len;
    var messages = Math.ceil(len / 160);
    if (len >= max) {
        $('#charNum').text('(' + messages + ') ' + len + '/' + max);
    } else {
        $('#charNum').text(len + '/' + max);
    }
    });
 -1
Author: Himali Kosty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 06:59:25

U puede usar:

    $(document).ready(function () {
  $('#ID').keyup(function () {
   var val = $(this).val();
   len = val.length;
   if (len >= 140) {
    $(this).text(val.substring(0, 140));
   } else {
    console.log(140 - len);
    $('#charNum').empty().append(140 - len);
   }
  });
 });
 -1
Author: demenvil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-22 12:28:25