开发者

Max characters in textarea with jquery

I have the following code, and I'm kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left. Once you get to the max cha开发者_开发问答racters I want to stop allowing characters to be entered, or delete all the characters that were entered so there are only 10 characters in the text area. I know I have to put the code where it says alert("LONG"); but I'm not quite sure what.

var maxLen = 10;
        console.log("Start");
        $('#send-txt').keyup(function(){
            var Length = $("#send-txt").val().length;
            var AmountLeft = maxLen - Length;
            $('#txt-length-left').html(AmountLeft);
            if(Length >= maxLen){
                alert("LONG");
            }



        });


All of these answers are a bit odd in that they try to do a little too much. A simpler and visually more pleasing way (because it shows the text quickly being cut off) - and with with less oddities that the previous example (note how it overwrites the final key?) - is to simply cut off the number of characters on keyUp to the number that's allowed.

var maxchars = 400;

$('body').on('keyup paste', 'textarea', function () {
    $(this).val($(this).val().substring(0, maxchars));
    var tlength = $(this).val().length;
    remain = maxchars - parseInt(tlength);
    $('#remain').text(remain);
});

Note that this then also works for pasting in text, as some of the examples above don't.

Example here: http://jsfiddle.net/PzESw/5/


Here it goes. Anything beyond character limit will be removed.

$('textarea').keypress(function(e) {
    var tval = $('textarea').val(),
        tlength = tval.length,
        set = 10,
        remain = parseInt(set - tlength);
    $('p').text(remain);
    if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $('textarea').val((tval).substring(0, tlength - 1));
        return false;
    }
})

Check working example at http://jsfiddle.net/JCehq/1/


Returning false and using .keypress() instead of .keyup() stops input once the length has been reached. Here's the example in a jsFiddle:

http://jsfiddle.net/p43BH/1/

Updated to allow backspace.


Got it with this:

$("#div_id").prop('maxlength', '80');

I really dont know if there's something wrong with this solution, but it worked for me.


A simple way to do this is to set the text in the textarea to a substring of the full amount. You can find an example here:

http://www.mediacollege.com/internet/javascript/form/limit-characters.html


If you change your js to look like this it should work for you:

var $txtLenLeft = $('#txt-length-left'); // lets cache this since it isn't changing
$('#send-txt').keydown(function(e) { //take the event argument
   var Length = $(this).val().length; // lets use 'this' instead of looking up the element in the DOM
   var AmountLeft = maxLen - Length;
   $txtLenLeft.html(AmountLeft);
   if(Length >= maxLen && e.keyCode != 8){ // allow backspace
      e.preventDefault(); // cancel the default action of the event
   }
});

You can see a working example here: http://jsfiddle.net/aP5sK/2/


ehm, textarea maxlength is a valid attribute in html5 ? not supported in ie9, thats all.

w3nerds http://www.w3.org/TR/html-markup/textarea.html#textarea.attrs.maxlength

w3fools http://www.w3schools.com/tags/att_textarea_maxlength.asp


Here's a solution using HTML5 data attribute to automatically bind to all needed textareas:

$('textarea[data-max-length]').live('keypress', function(e) {
    if (String.fromCharCode(e.charCode || e.keyCode).match(/\S/) && $(this).val().length >= $(this).attr('data-max-length')) {
        e.preventDefault();
    }
});


I know this is a little late, but I just had to figure this out, too. I had to get it to work with UTF8 byte-lengths, and allow certain keypresses. Here's what I came up with:

checkContent = function (event) {

    var allowedKeys = [8,46,35,36,37,38,39,40];
    var contentLength = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    var charLength = lengthInUtf8Bytes(String.fromCharCode(event.charCode));

    if (charLength + contentLength > 20) {

        if(jQuery.inArray(event.keyCode, allowedKeys) == -1) {
            event.preventDefault();
        } 
    }
}

countLength = function(event) {

    var len = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    jQuery('#length').html(len);
}


lengthInUtf8Bytes = function(str) {
    var m = encodeURIComponent(str).match(/%[89ABab]/g);
    return str.length + (m ? m.length : 0);
}

jQuery(function(){jQuery("#textarea").keypress(function(event){checkContent(event)}).keyup(function(event){countLength(event)})});

You need to have a textarea with id #textarea and an element to display the current length with id #length.

The keypress event determines whether or not to allow the keypress. The keyup event counts the size of the data in the field after the keypress is allowed/prevented.

This code works with the following keys: home, end, pagedown, pageup, backspace, delete, up, down, left and right. It doesn't deal with pasting from the clipboard.

Hope someone finds it useful!


Relying on keypress, keydown, keyup is a flawed solution because a user can copy and paste data into the textarea without pressing any keys.

To limit the length of text in a textarea with javascript regardless of how the data gets in there you must rely on a setInterval timer instead.

setInterval(function() {
if ($('#message').val().length > 250) {
    $('#message').val($('#message').val().substring(0, 250));
}}, 500);

Obviously, I'm assuming you have an id of message assigned to your textarea.


try this.

var charLmt = "200";//max charterer 
 $("#send-txt").keydown(function(){
   var _msgLenght = $(this).val().length;
   if (_msgLenght > charLmt) {
   $(this).val($(this).val().substring(0, charLmt));
  }
});


$("#message-field").on("keyup paste", function() {
  var $this, limit, val;
  limit = 140;
  $this = $(this);
  val = $this.val();
  $this.val(val.substring(0, limit));
  return $('#character-remaining').text(limit - $this.val().length);
});


Try this. Even works for copy paste from Keyboard:

$("#comments").unbind('keyup').keyup(function(e){
    var val = $(this).val();
    var maxLength = 1000;
    $('#comments').val((val).substring(0, maxLength));
    $("#comments_length").text($("#comments").val().length);
});


I find this works perfectly, and doesn't even flash the excess characters in the textarea before removing them, as a few other solutions do.

<h1>Add a comment:</h1>
<form>
    <textarea name="commentText" id="commentText"></textarea>
</form>
<br><span id="commentChars">1000</span> characters remaining

<script type="text/javascript">

    function checkChars(){
        var numChars = $('#commentText').val().length;
        var maxChars = 1000;
        var remChars = maxChars - numChars;
        if (remChars < 0) {
            $('#commentText').val($('#commentText').val().substring(0, maxChars));
                remChars = 0;
            }
        $('#commentChars').text(remChars);
    }

    $('#commentText').bind('input propertychange', function(){
        checkChars();
    });

    checkChars();

</script>


I think best way using maxlenght property + jquery keydown, keyup, paste events

// text input maximum lenght
$(document).on('keydown keyup paste', 'input[type=text]', function(e) {
  var textArea = $('input[type=text]').val(),
    textLenght = textArea.length,
    limit = $('textarea').attr('maxlength'),
    remain = 'left ' + parseInt(limit - textLenght) + ' chars';
  $('#remain-title').text(remain);
  if (textLenght > 500) {
    $('textarea').val((textArea).substring(0, limit))
  }
});

// tex area maximum lenght
$(document).on('keydown keyup paste', 'textarea', function(e) {
  var textArea = $('textarea').val(),
    textLenght = textArea.length,
    limit = $('textarea').attr('maxlength'),
    remain = 'left ' + parseInt(limit - textLenght) + ' chars';
  $('#remain-description').text(remain);
  if (textLenght > 500) {
    $('textarea').val((textArea).substring(0, limit))
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>Title</label>
  <p id="remain-title"></p>
  <input type="text" placeholder="Enter Title" maxlength="500"/>
</div>
<br>
<hr>
<br>
<div>
  <label>Description</label>
  <p id="remain-description"></p>
  <textarea placeholder="Enter custom description" rows="4" maxlength="500"></textarea>
</div>

See JSFiddle


In 2020 in most browsers limiting characters in textarea is supported by one helpful attribute maxlength check at w3chools

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜