Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

text - Countdown available spaces in a textarea with jquery or other?

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...