2

I have a text field, I am using onkeypress to check the length of the entered string. If it exceeds n number of characters it will return false and it will not accept any other character, But Here I am unable to remove the characters I don't want in thetext field. How can I remove the text here.

4

3 回答 3

3

试试这个,如果你正在使用textarea

<textarea onkeypress="return limitlength(this, 20)" style="width: 300px; height: 90px"></textarea>

 function limitlength(obj, length){
    var maxlength=length
    if (obj.value.length>maxlength)
     obj.value=obj.value.substring(0, maxlength)
 }
于 2013-09-05T07:47:48.870 回答
1

使用简单的 HTML5,不需要 javascript:

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

MDN

于 2013-09-05T07:55:46.027 回答
0

检查 Onkeyup 事件中输入文本的长度。如果它大于 n 则使用子字符串截断前 n 个字符,然后将新字符串设置为值

   $("#mytxt").onkeyup(function(){

 var Currentlength =$(this).val().length;
 var CurrentVal = $(this).val();
 if(Currentlength > n)
 {
  $(this).val(CurrentVal.substring(0,n));
  return false;
 } 
});
于 2013-09-05T07:49:15.907 回答