views:

989

answers:

8

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.

+1  A: 

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))
});
tghw
Interesting, near identical code :)
karim79
I think I was just 20 seconds before you. Great minds?
tghw
+1  A: 

Off the top of my head:

    $('#myTextArea').keyup(function() {
        var text = $(this).text();
        if(text.length == 141) {
            $(this).text(text.substring(text.length - 2));
        }
    });
karim79
What's wrong with this? What's with the down vote?
Aaron Maenpaa
I am not the down-voter. The problem that I see is that long pasted text can get passed the length check.
Borgar
length check should be as per tghw's , if a key is held and the character repeats you may not get a keyup event until it has exceeded the 141 characters
TygerKrash
+2  A: 

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));

});
Steve Willcock
What if somebody inserts a char in the middle of 140 char string?
Mehrdad Afshari
@Mehrdad good point :)
Yasir
@Mehrdad You could accomplish that by saving the text on keyup and using the saved text instead of substring to restore the text when you hit 141 characters.
Aaron Maenpaa
Yes, currently this would just lose the last character at the end if someone starts typing in the middle of the string. It depends on your required behaviour.
Steve Willcock
What if the user enters text without using the keyboard?
recursive
+2  A: 

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

kennebec
+8  A: 

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.

DisgruntledGoat
A: 
$(document).ready(function() {
        var maxLimit = 140;
        $('#txtIdInput').keyup(function() {
        var length = $('#txtIdInput').val().length;
            if (length > maxLimit) {
                $("#txtIdInput").val($("#txtIdInput").val().substring(0, maxLimit));
            }
        });

    });
Shiva
A: 

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;
    }
});
Borgar
+4  A: 

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);
});
Mr. Shiny and New
+1 Silently modifying users' input is very confusing to people. Plus, without server-side validation, input validation for the sake of security is pointless anyway.
Rob Hruska
perfect although my app will not deal with financial but you did good advise and just implemented your solution Thanks
Yasir
Glad I could help.
Mr. Shiny and New