How to remove characters from a text field when the number of characters exceeds a certain limit?

I would like to implement a text box with a limit of 140 characters in Javascript so that when the 141st character is added, that character will be deleted.

I do not want to show any message or warning to the user that they have exceeded the limit. There is already counter.re.

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

I use jQuery, if it already has this function, let me know.

+3
source share
8 answers

, , . , , - . , -

1223300045

122330045

, ,

122330004

. .

- StackOverflow. , , , , , , , , . :

  • , , ,
  • , ,
  • .

, - , , , , . . , , / , . , . ; ( - ). , - . .

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);
});   
+5

, maxlength:

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

, . , , , .

+10

, TextArea, - .

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

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

});
+3

, - onchange onblur, .

, 141- .

, .

+2

Assuming you are using textareaone that has no built in maxlength, you can simply assign an event keyup:

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

Above my head:

    $('#myTextArea').keyup(function() {
        var text = $(this).text();
        if(text.length == 141) {
            $(this).text(text.substring(text.length - 2));
        }
    });
+1
source
$(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
source

Topic Option:

$("#textarea").keyup(function(e) {
    var trim = this.value.substr( 0, 140 );  // "foo".substr(0, 140) == "foo"
    if ( this.value != trim ) {
      this.value = trim;
    }
});
0
source

Source: https://habr.com/ru/post/1706281/


All Articles