How to make a character counter of a textarea?

Asked

Viewed 33,239 times

11

I tried to make one, but always ran into some limitation. I think my logic will not work, but I still could not think of another.

Javascript:

$(document).on("keydown", "#TxtObservacoes", function () {
    var caracteresRestantes = 255;
    var caracteresDigitados = parseInt($(this).val().length);
    var caracteresRestantes = caracteresRestantes - caracteresDigitados;

    $(".caracteres").text(caracteresRestantes);
});

HTML:

<span class="caracteres">255</span> Restantes <br>
<textarea id="TxtObservacoes"></textarea>

My code: http://jsfiddle.net/5pw5L/

  • Ta further what are the limitations of its implementation? Just to understand the problem.

  • If I use keydown the textarea has not yet added the typed text and the wrong account. If I use keypress it does not detect Backspace for example. In the fiddle you can see that.

5 answers

16


Change the keydown event to input.

Take the example:

$(document).on("input", "#TxtObservacoes", function () {
    var limite = 255;
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite - caracteresDigitados;

    $(".caracteres").text(caracteresRestantes);
});

I also changed the name of one of the variables, as a suggestion.

The input event covers several text input cases, such as copying and pasting and holding down a key. Other events end up generating the need for more code, complicating the problem.

Alternatively, if you need to support versions of browsers that do not implement the input event, use the keyup event. You can add both events in the method .on() jQuery:

$(document).on("input keyup", "#TxtObservacoes", function () {
...
  • 5

    The event input is a great option, it also works if a text is pasted into the field (no keyboard use).

  • Thanks @bfavaretto, I used the input here and it was great.

  • I will change to recommend only the use of input, since it covers more cases, as described by @bfavaretto.

  • 2

    It may be necessary to use a combination of events, as the input may not be supported, depending on the browser and the situation.

  • I added a note as per the @bfavaretto comment, regarding the input event not being implemented in some browsers.

  • @Bernardobotelho, is ("input keyup") without comma between themselves?

  • Yes, no comma, with space.

  • 3

    @Bernardobotelho can (must) use this.value.length instead of $(this).val().length. The less jQuery the better.

Show 3 more comments

2

This solution is simple and complete :)

http://jsfiddle.net/kyodesign/3zheoyj5/

jQuery

$(document).on("input", "#comentario", function() {
    var limite = 145;
    var informativo = "caracteres restantes.";
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite - caracteresDigitados;

    if (caracteresRestantes <= 0) {
        var comentario = $("textarea[name=comentario]").val();
        $("textarea[name=comentario]").val(comentario.substr(0, limite));
        $(".caracteres").text("0 " + informativo);
    } else {
        $(".caracteres").text(caracteresRestantes + " " + informativo);
    }
});

1

This is a functional example of character counting in a textarea.

HTML

<span id="cont">50</span> Restantes <br>
<textarea onkeyup="limite_textarea(this.value)" id="texto"></textarea>

Javascript

   function limite_textarea(valor) {
    quant = 50;
    total = valor.length;
    if(total <= quant) {
        resto = quant - total;
        document.getElementById('cont').innerHTML = resto;
    } else {
        document.getElementById('texto').value = valor.substr(0,quant);
    }
}

The function:

The variable Quant delimits the maximum number of characters to be filled in Total receives the number of characters already typed in the field. Check if the total is less than or equal to the quantity, to see if it can still be filled in. Rest receives the subtraction of Quant minus the total to display how many characters can still be filled in. Then write in the < span id="cont"> the number of characters remaining. And if the amount is higher, it will block typing, by releasing the key the script will pick up all characters that are smaller than the amount.

The textarea field:

The only need in this field is that it has these two parameters: onkeyup="limite_textarea(this.value)" -- call the function when you release a key. id="texto" -- field id - for identification

0

var fieldArea = document.getElementById('countCharacters');
    var msgLimit = "Limite de carácteres excedido"; 

    if (fieldArea) {
        var countCharacters = fieldArea.onkeydown = function(e){
            var fieldMaxLength = fieldArea.maxLength;
            var fieldValueLength = fieldArea.value.length;

            var result = document.getElementById('result');

            var equation = fieldMaxLength - fieldValueLength;

            //Se os carácteres digitados for menor ou igual ao maxlength
            if (fieldValueLength <= fieldMaxLength) {
                result.innerText = equation + " carácteres restantes";
            }
            //Se os carácteres digitados tiver alcançado o maxlength
            if (fieldValueLength == fieldMaxLength) {
                result.innerText = msgLimit;
            }
            console.clear();
            console.log(fieldMaxLength);
            console.log(fieldValueLength);
            console.log(equation);          
        }       

        countCharacters();
    }

-1

following the code of our friend adrianoAcosta, I also manipulated the color red when you are reaching the limit of characters

$(document).on("input", "#comentario", function() {
	var limite = 145;
    var informativo = "caracteres restantes.";
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite - caracteresDigitados;

    if (caracteresRestantes <= 0) {
        var comentario = $("textarea[name=comentario]").val();
        $("textarea[name=comentario]").val(comentario.substr(0, limite));
        $(".caracteres").text("0 " + informativo);
    } else if (caracteresRestantes >= 16) {
		$( ".caracteres" ).css( "color", "#000000" );
        $(".caracteres").text(caracteresRestantes + " " + informativo); 
	} else if (caracteresRestantes >= 0 && caracteresRestantes <= 15) {
		$( ".caracteres" ).css( "color", "red" );
        $(".caracteres").text(caracteresRestantes + " " + informativo); 
	} else {
		$(".caracteres").text(caracteresRestantes + " " + informativo);
	}
}); 
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>


<p><label for="review">Seu comentário</label> <small class="caracteres"></small></p>
<textarea name="comentario" id="comentario" cols="30" rows="10"></textarea>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.