如何使用JavaScript在HTML中的textArea上强加maxlength

Rak*_*yal 115 html javascript textarea

如果我写的话,我想有一些功能

<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>
Run Code Online (Sandbox Code Playgroud)

它会自动在textArea上施加maxlength.如果可能请不要在jQuery中提供解决方案.

注意:如果我这样做,可以这样做:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">

function imposeMaxLength(Event, Object, MaxLen)
{
    return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
Run Code Online (Sandbox Code Playgroud)

复制在HTML textarea上模拟HTML输入"maxlength"属性的最佳方法是什么?

但问题是我每次声明textArea时都不想写onKeyPress和onKeyUp.

Jos*_*ola 111

window.onload = function() { 
  var txts = document.getElementsByTagName('TEXTAREA'); 

  for(var i = 0, l = txts.length; i < l; i++) {
    if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { 
      var func = function() { 
        var len = parseInt(this.getAttribute("maxlength"), 10); 

        if(this.value.length > len) { 
          alert('Maximum length exceeded: ' + len); 
          this.value = this.value.substr(0, len); 
          return false; 
        } 
      }

      txts[i].onkeyup = func;
      txts[i].onblur = func;
    } 
  };

}
Run Code Online (Sandbox Code Playgroud)

  • 我切换了警报的顺序和值截断 - 按原始顺序,onkeyup将发出警报,导致控件失去焦点,并且因为字段尚未被截断而触发onb​​lur. (7认同)
  • Josh似乎它会起作用,但请你解释一下这件事会做什么--- if(/ ^ [0-9] + $/.test(txts [i] .getAttribute("maxlength"))){ - - (3认同)
  • @JoshStodola - 确实你不能.如果我在textarea中粘贴了一些东西,点击提交,并且只看到其中的一小部分没有任何响应,那真的会让我感到厌烦. (3认同)
  • 我想我记得这笔交易是什么:当Javascript检查"value"属性时,FF或IE(我认为它是FF)返回一个不同的字符串,而不是它在发布表单时发送回服务器的属性!它与强行换行如何/没有插入回车字符有关.在客户端和服务器端很容易弄清楚一些调试代码. (2认同)

Eir*_*k W 80

我知道你想避免使用jQuery,但由于解决方案需要JavaScript,因此这个解决方案(使用jQuery 1.4)是最简洁和最强大的.

受到启发,但对Dana Woodman的回答有所改进:

这个答案的变化是:简化和更通用,使用jQuery.live,如果长度正常,也不设置val(导致IE中的工作箭头键,以及IE中的显着加速):

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:jQuery 1.7+的更新版本,使用on而不是live

// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
    // Store the maxlength and value of the field.
    var maxlength = $(this).attr('maxlength');
    var val = $(this).val();

    // Trim the field if it has content over the maxlength.
    if (val.length > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 但如果他们在中间进行编辑,这会杀死最后一个角色,而不是新角色,对吗? (6认同)
  • 是的,用在()上它就像一个宝石.谢谢.这是一个经过修改和调整的小提琴:http://jsfiddle.net/nXMqc/ (6认同)
  • 切片的问题是,如果您在中间输入字符,则会插入它们,并从末尾剪切字符串.如果一次看不到整个文本,这可能会令人困惑.同样使用val(..)函数来更改值似乎将光标移动到字符串的末尾.(如果你想用小提琴中的现代浏览器测试这些,你需要删除maxlength属性 - 否则浏览器将强制执行限制). (6认同)
  • 我发现live()中的bug和jQuery已经弃用了它.使用on()代替.如果您关心原因:http://www.britishdeveloper.co.uk/2012/04/jquery-dont-use-bind-and-dont-use-live.html (5认同)

Dan*_*man 33

更新使用Eirik的解决方案,.live()因为它更健壮.


即使你想要一个不使用jQuery的解决方案,我想我会为通过Google找到这个页面并寻找jQuery-esque解决方案的人添加一个:

$(function() {        
    // Get all textareas that have a "maxlength" property.
    $('textarea[maxlength]').each(function() {

        // Store the jQuery object to be more efficient...
        var $textarea = $(this);

        // Store the maxlength and value of the field.
        var maxlength = $textarea.attr('maxlength');
        var val = $textarea.val();

        // Trim the field if it has content over the maxlength.
        $textarea.val(val.slice(0, maxlength));

        // Bind the trimming behavior to the "keyup" event.
        $textarea.bind('keyup', function() {
            $textarea.val($textarea.val().slice(0, maxlength));
        });

    });
});
Run Code Online (Sandbox Code Playgroud)

希望对你有用的Google员工......


jam*_*iss 31

HTML5 maxlengthtextarea元素添加了一个属性,如下所示:

<!DOCTYPE html>
<html>
    <body>
        <form action="processForm.php" action="post">
            <label for="story">Tell me your story:</label><br>
            <textarea id="story" maxlength="100"></textarea>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Chrome 13,FF 5和Safari 5目前支持此功能.毫无疑问,IE 9不支持此功能.(在Win 7上测试过)


Chr*_*s R 5

此解决方案避免了IE中的问题,其中当添加文本中间的字符时删除最后一个字符.它也适用于其他浏览器.

$("textarea[maxlength]").keydown( function(e) {
    var key = e.which;  // backspace = 8, delete = 46, arrows = 37,38,39,40

    if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;

    return $(this).val().length < $(this).attr( "maxlength" );
});
Run Code Online (Sandbox Code Playgroud)

我的表单验证然后处理用户可能粘贴的任何问题(在IE中似乎只是一个问题)文本超过textarea的最大长度.