How can I lock the keyboard to limit the number of characters in a textarea?

隐身守侯 提交于 2019-12-25 00:43:04

问题


The following code works great for locking the keyboard in IE6 and IE8 when a textarea reaches a certain length. Of course, it doesn't work on other browsers, and I can't figure out a way to turn it into a jQuery function that will work cross-browser. Is it possible to get the same behavior in FireFox and Webkit browsers?

function checkLength(fld, maxLength){
    if(fld.value.length > maxLength-1){
        event.returnValue = false;
    }
}

<p><textarea name="third" id="third" onkeypress="checkLength(this, 10);">hello</textarea></p>

回答1:


I'm going to plug my own blog here -

http://blog.jbstrickler.com/2010/11/textarea-size-limit-w-counter/

If you want something very simple, you could do -

<textarea onkeypress="return (this.value.length < 50);"></textarea>

Where 50 is how many characters you want to limit.

EDIT: Per Jason's comment, I didn't want to give the wrong impression here that inline scripting is okay...

$('textarea').keypress(function() {
  return $(this).val().length < 50;
});



回答2:


Here's a link to somebody who has done just that, with both jQuery and plain Javascript versions: http://www.ajaxray.com/blog/2007/11/09/interactive-character-limit-for-textarea-using-jquery/

Hope that helps!



来源:https://stackoverflow.com/questions/5794734/how-can-i-lock-the-keyboard-to-limit-the-number-of-characters-in-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!