Countdown available spaces in a textarea with jque

2019-01-16 10:17发布

问题:

I have a few areas on my site where I need to limit text input to X amount of characters and it's nice to show a number of spaces left while a user types in, like twitter does.

I found this jquery plugin; jquery max-length plugin

It does just what I need but it seems kind of like overkill, I am not sure the filesize but it looks like a lot of lines of code for such a simple task, do you think I would be better off using a non-jquery method? The reason I was thinking jquery was the way to go is because jquery is already included into all my pages UPDATE;

I just found this non-jquery method that does the exact same thing is is way smaller footprint, so would this be the better method?

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
   if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
   } else {
    limitCount.value = limitNum - limitField.value.length;
   }
}
</script>

You have 
<input readonly type="text" name="countdown" size="3" value="1000">
characters left.

回答1:

Very simple in jQuery:

<textarea id="myTextarea"></textarea>
<p id="counter"></p>

<script type="text/javascript">
$('#myTextarea').keyup(function () {
    var left = 200 - $(this).val().length;
    if (left < 0) {
        left = 0;
    }
    $('#counter').text('Characters left: ' + left);
});
</script>

Substitute the 200 by whatever your limit is.

Note this does not limit the actual text input, it just counts down. You need to check server-side for the input length, this is just a visual helper.

As an aside, I don't think you even should try to limit the input length by denying any input when the limit is reached. It's a pain in the rear usability-wise and can't be relied upon anyway. A simple countdown and server-side checking is the best option IMHO.



回答2:

Sometimes you need to have more than one text area and want them addressed individually without having to code for each. This code dynamically adds the chars remaining to any having a maxLength attribute...

<script type="text/javascript">
$(document).ready(function(){
    $('textarea[maxLength]').each(function(){
        var tId=$(this).attr("id");
        $(this).after('<br><span id="cnt'+tId+'"></span>');
        $(this).keyup(function () {
            var tId=$(this).attr("id");
            var tMax=$(this).attr("maxLength");//case-sensitive, unlike HTML input maxlength
            var left = tMax - $(this).val().length;
            if (left < 0) left = 0;
            $('#cnt'+tId).text('Characters left: ' + left);
        }).keyup();
    });
});
</script>
<textarea id="myTextarea" maxLength="200">Initial text lorem ipsum blah blah blah</textarea><br><br>
<textarea id="mySecondTextarea" maxLength="500"></textarea><br><br>
<textarea id="textareaWithoutCounter"></textarea>


回答3:

I've used Aaron Russell's simply countable jQuery plugin with success

Simple usage:

$('#my_textarea').simplyCountable();

Advanced usage:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});


回答4:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function()
        {
            $('#TestId').keyup(function(e)
            {
                var maxLength = 100;
                var textlength = this.value.length;
                if (textlength >= maxLength)
                {
                    $('#charStatus').html('You cannot write more then ' + maxLength + ' characters!');
                    this.value = this.value.substring(0, maxLength);
                    e.preventDefault();
                }
                else
                {
                    $('#charStatus').html('You have ' + (maxLength - textlength) + ' characters left.');
                }
            });
        });
    </script>
</head>
<body>
    <textarea id="TestId" cols="20" rows="8"></textarea><br />
    (Maximum characters: 100)<br />
    <span id="charStatus"></span>   
</body>
</html>


回答5:

 var max = 140;
        $("#spn").html(max+"  Remaining");
        $("#textarea").keyup(function () {
            var lenght1 = $("#textarea").val().length;
            var remaining = max - lenght1;
            $("#spn").html(remaining + "  Remaining");
            if (remaining < 0) { $("#spn").css('opacity', '0.4').css('color', 'red'); $("#comment").attr('disabled', 'disabled'); } else { $("#spn").css('opacity', '1').css('color', 'black'); $("#comment").removeAttr('disabled'); }
            if (remaining < 10) { $("#spn").css('color', 'red'); } else { $("#spn").css('color', 'black'); }

        });


回答6:

I used jQuery and the answer by deceze and then tweaked it to give me a twitter-style countdown so that users could see by how much they had gone over and adjust their text accordingly. I also put it into its own function so I could call it from another function that sometimes populated the textarea automatically:

    function reCalcToText() {
        var left = 200 - $('.toText').val().length;
        if (left < 0) {
            $('#counter').text(left);
            $('#counter').addClass("excess");
        } else {
            $('#counter').text(left);
            $('#counter').removeClass();
        }
    }
    function onReady() {
                  $('#<%= toText.ClientID %>').keyup(function() {
            reCalcToText();
        });
    };


回答7:

So I took @deceze version and added a bit of trick to make it:

  • show always and not only when the user starts typing,
  • show minus when the limit is over, and
  • add class - to color the text - when it is over the limit (extra css is needed for this of course)

    $(document).ready(function(){
        var left = 200
        $('#field_counter').text('Characters left: ' + left);
    
            $('#id_description').keyup(function () {
    
            left = 200 - $(this).val().length;
    
            if(left < 0){
                $('#field_counter').addClass("overlimit");
            }
            if(left >= 0){
                $('#field_counter span').removeClass("overlimit");
            }
    
            $('#field_counter').text('Characters left: ' + left);
        });
    });
    

For anyone needing the same as me :)



回答8:

Using jQuery, assuming that you have a textarea with id field that you wish to limit to 100 characters, and another element with id chars-remaining to display the number of available characters:

var max = 100;
$('#field').keyup(function() {
    if($(this).val().length > max) {
        $(this).val($(this).val().substr(0, max));
    }
    $('#chars-remaining').html((max - $(this).val().length) + ' characters remaining');
});


回答9:

Keep in mind that you have to account for NewLines being 2 characters.
I built upon the solutions provided here to the below code which accounts for new lines.

function DisplayCharactersLeft(idOfInputControl) {
    var maxNumberOfCharacters = $("#" + idOfInputControl).attr("maxLength");

    $("#" + idOfInputControl).on("input", function () {
        var currentText = $(this).val();
        var numberOfNewLines = GetNumberOfNewLines(currentText);

        var left = maxNumberOfCharacters - (currentText.length + numberOfNewLines);
        if (left < 0) { left = 0; }
        $("#" + idOfInputControl + "CharactersLeftCounter").text("Characters left: " + left);
    });

}    

function GetNumberOfNewLines(text) {

    var newLines = text.match(/(\r\n|\n|\r)/g);
    var numberOfNewLines = 0;
    if (newLines != null) {
        numberOfNewLines = newLines.length;
    }
    return numberOfNewLines;
}


标签: jquery text max