最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I remove characters from a textbox when the number of characters exceeds a certain limit? - Stack Overflow

programmeradmin3浏览0评论

I would like to implement a text box with a 140 character limit in Javascript such that when the 141st character is added that character is erased.

I don't want to show any message or alert to user they have exceeded the limit. There is already a counter.re.

Here is an example of what I want to do: /

I am using jQuery, if it already has this functionality please let me know.

I would like to implement a text box with a 140 character limit in Javascript such that when the 141st character is added that character is erased.

I don't want to show any message or alert to user they have exceeded the limit. There is already a counter.re.

Here is an example of what I want to do: http://titletweets.com/category/games/michigan-state-vs-north-carolina/

I am using jQuery, if it already has this functionality please let me know.

Share Improve this question edited Apr 11, 2009 at 22:49 Aaron Maenpaa 123k11 gold badges97 silver badges108 bronze badges asked Apr 11, 2009 at 21:54 YasirYasir 3,90710 gold badges38 silver badges42 bronze badges 1
  • I suggest you go with a notification message instead. You might want to edit your string and make it under 140char but the limit will make editing a pain. – Mehrdad Afshari Commented Apr 11, 2009 at 22:19
Add a comment  | 

8 Answers 8

Reset to default 10

If it's a single line textbox then you can use the maxlength attribute:

<input type="text" maxlength="140" />

It's also worth noting that whatever your solution, you still need to repeat validation on the server-side. Whether you report back to the user that their entry was too long or you simply truncate the data is up to you.

A bank in Scandinavia recently had a lawsuit because a customer accidentally transferred a pile of money to the wrong account because she typed in too many zeros into the account number. This made the resulting account number invalid, however she didn't notice because the web-application silently erased her extra digit. So she entered something like

1223300045

but should have entered

122330045

and consequently account

122330004

received her money. This is a major usability flaw.

In the case of something like a text-area, take a look at StackOverflow's own comments UI. It shows you how much text is in your textbox, and you have the opportunity to edit your text, but the really sweet part is that you can type as much as you want, then edit down to the bare limit, letting you ensure you can say all you like. If your text box erases the user's text:

  • They may not notice it happening, if they type by looking at the keyboard
  • They have to erase text before they can add new, more concise wording
  • They will be annoyed

Thus, my recommendation is to let the user type as much they want, but let them know when they are over the limit, and let them edit. The following sample can get you started. You should change the selectors as appropriate to only manipulate the textareas/text inputs you need to. And don't forget to do the appropriate thing if the limit is wrong. This sample sets a class; the class attribute lets you change the colour of the textarea (or whatever). You might want to show a message or something. They key is to let the user keep typing.

function checkTALength(event) {
  var text = $(this).val();
  if(text.length > 140) {
    $(this).addClass('overlimit');
  } else {
    $(this).removeClass('overlimit');
  }
}
function checkSubmit(event) {
  if($('.overlimit', this).length > 0) { return false; }
}

$(document).ready(function() {   
  $('textarea').change(checkTALength);
  $('textarea').keyup(checkTALength);
  $('form').submit(checkSubmit);
});   

Assuming the id of the text area is theTextArea, something like this should work.

$("#theTextArea").keyup(function(event) {

    var text = $("#theTextArea").val();
    if (text.length > 140)
        $("#theTextArea").val(text.substring(0, 140));

});

The keyup won't prevent a right click paste operation that could go over the limit- you may want to set the value onchange or onblur as well as on the keystroke.

If you handle the event from keydown, before the keypress, you can avoid the flashing 141st letter.

Or if this is a text input element. set the maxlength

Assuming you're using a textarea, which doesn't have a built-in maxlength, you can just assign a keyup event:

$('#tweet').keyup(function(){
  var s = $(this).text();
  if(s.length > 140)
    $(this).text(s.substring(0,140))
});

Off the top of my head:

    $('#myTextArea').keyup(function() {
        var text = $(this).text();
        if(text.length == 141) {
            $(this).text(text.substring(text.length - 2));
        }
    });

A variation on a theme:

$("#textarea").keyup(function(e) {
    var trim = this.value.substr( 0, 140 );  // "foo".substr(0, 140) == "foo"
    if ( this.value != trim ) {
      this.value = trim;
    }
});
$(document).ready(function() {
        var maxLimit = 140;
        $('#txtIdInput').keyup(function() {
        var length = $('#txtIdInput').val().length;
            if (length > maxLimit) {
                $("#txtIdInput").val($("#txtIdInput").val().substring(0, maxLimit));
            }
        });

    }); 
发布评论

评论列表(0)

  1. 暂无评论