设置文本区域中的最大字符数


Set the max amount of chars in a textarea

我试图限制可以添加到文本区域的字符数。我知道我可以用一个子字符串来计算字符数,但我想告诉用户他的文本已经达到了最大长度。

maxlength属性似乎正是我想要的,但IE在我们当前的版本上不支持它(我认为它在IE9附近得到了支持)

为了解决这个问题,我集成了onKeyPress="return(this.value.length < 160);",它可以很好地防止过长的文本,但它也可以防止文本的擦除或重新编辑,这是一个巨大的问题。

只需添加这个javascript,它对我来说很有用,对查看左侧字符也很有用。

function textCounter(field,cntfield,maxlimit) { 
    if (field.value.length > maxlimit) // if too long...trim it!
    {field.value = field.value.substring(0, maxlimit); }
    // otherwise, update 'characters left' counter
    else
    {       
    //cntfield.value = maxlimit - field.value.length; 
    cntfield.value = field.value.length
    }
}

html file

此外,请添加以下跨度的文本区域的onKeypress事件,以管理剩余字符

<span class="alignright comments-req"><input type="text" name="textlen" id="textlen" value="0" class="counter-textfield">/500 <?php  echo $this->translate('LABEL_CHARACTER_USED');?></span>
    You can use jquery validation check this link
 http://jqueryvalidation.org/maxlength-method/

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Makes "field" required having at most 4 characters.</title>
    <link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/site-demos.css">
    </head>
    <body>
    <form id="myform">
    <label for="field">Required, maximum length 4: </label>
    <input type="text" class="left" id="field" name="field">
    <br/>
    <input type="submit" value="Validate!">
    </form>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
    <script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
    <script>
    // just for the demos, avoids form submit
    jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
    });
    $( "#myform" ).validate({
      rules: {
        field: {
          required: true,
          maxlength: 4
        }
      }
    });
    </script>
    </body>
    </html>