Character countdown like on twitter

2020-01-29 03:36发布

How can I make a "remaining characters" countdown like the one on Twitter with jQuery? And also limit the input to a textarea.

9条回答
一纸荒年 Trace。
2楼-- · 2020-01-29 03:50

Make a span and textarea and give them unique selectors (using an ID or class) like so:

<textarea class="message" rows="2" cols="30"></textarea>
<span class="countdown"></span>

And then make an update function like so:

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('.message').val().length;
    jQuery('.countdown').text(remaining + ' characters remaining.');
}

And make that function run when the page is loaded and whenever the message is changed:

jQuery(document).ready(function($) {
    updateCountdown();
    $('.message').change(updateCountdown);
    $('.message').keyup(updateCountdown);
});

Visit an example and view the source. jQuery makes things like this very simple.

查看更多
虎瘦雄心在
3楼-- · 2020-01-29 03:51

In my implementation, I added the following JS function:

function charactersRemaining(elementID, messageElementID, maxCharacters)
{
    var remaining = maxCharacters - $('#' + elementID).val().length;
    $('#' + messageElementID).text(remaining + ' characters remaining.');
}

Then I could reuse that function all over the application (for example, if I had the following HTML):

<textarea class="form-control" asp-for="Comments" rows="3"></textarea>
<span id="commentsCharsRemaining" class="text-primary"></span>

Just add these 2 jquery statements to make it work:

$('#Comments').change(function () {
    charactersRemaining('Comments', 'commentsCharsRemaining', 2000)
});
$('#Comments').keyup(function () {
    charactersRemaining('Comments', 'commentsCharsRemaining', 2000)
});
查看更多
我命由我不由天
4楼-- · 2020-01-29 03:51

use jquery

save this as jquery.textlimiter.js

(function($) {
    $.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);
        }
    });
})(jQuery);

usage

<textarea id="text" maxlength="100" cols="50" rows="5" placeholder="Enter Text"></textarea>
    <div id="chars">100</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="path/to/jquery.textlimiter.js"></script>
<script>
$(document).ready( function() {
    var elem = $("#chars");
    $("#text").limiter(100, elem);
});
</script>
查看更多
劫难
5楼-- · 2020-01-29 03:54

I've used Aaron Russell's simply countable jQuery plugin with success; though, if I were to have written it, I would have designed it a bit differently (automatic counter div creation, using a data-maxlength attribute instead of a plugin option, etc).

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: ','
});
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-01-29 03:57

HTML:

<form>
    <!-- remember to markup your forms properly using labels! -->
    <label for="textareaChars">No more than 100 characters</label>

    <textarea id="textareaChars" maxlength="100"></textarea>

    <p><span id="chars">100</span> characters remaining</p>

</form>

JS:

$( document ).ready(function() {
    var maxLength = 100;
    $('textarea').keyup(function() {
        var length = $(this).val().length;
        var length = maxLength-length;
        $('#chars').text(length);
    });
});
查看更多
淡お忘
7楼-- · 2020-01-29 04:03

I added a simple pluralize function, cus nobody likes bad grammar.

function pluralize(count, word){
  if (count == 1 || count == -1){
    return String(count) + ' ' + word;
  }else{
    return String(count) + ' ' + word + 's';
  }
}

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('#micropost_content').val().length;
    jQuery('.countdown').text(pluralize(remaining,'character') + ' remaining');
}

...
查看更多
登录 后发表回答