Javascript 计算输入字符 - 使用 onkeyup 还是 onkeydown?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7165273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting input chars - use onkeyup or onkeydown?
提问by Naftali aka Neal
I need to set the maximum character input for users simililar to how stackoverflow.com works. I plan on using javascript to provide feedback to the user and count the characters. Only submissions that don't exceed the maximum character count are allowed. I don't plan on using the xhtml input properties to limit this amount as I'll allow overage on characters as long as they are not submitted. On the backend I'll just set the varchar field in mysql to charmax.
我需要为类似于 stackoverflow.com 的工作方式的用户设置最大字符输入。我计划使用 javascript 向用户提供反馈并计算字符数。只允许提交不超过最大字符数的提交。我不打算使用 xhtml 输入属性来限制这个数量,因为只要不提交字符,我就会允许字符超量。在后端,我只需将 mysql 中的 varchar 字段设置为 charmax。
Question is, how do I count character inputs, do I base it off of onkeydown() or onkeyup(). I'm not too sure why there are two functions, because a key that goes down must come up, so which one should I use to do the counting?
问题是,我如何计算字符输入,是基于 onkeydown() 还是 onkeyup()。我不太清楚为什么有两个功能,因为一个向下的键必须出现,那么我应该使用哪个来进行计数?
回答by GolezTrol
Use document.getElementById('YourInputBoxId').value.length
to get the length of the text.
使用document.getElementById('YourInputBoxId').value.length
来获取文本的长度。
Don't use the keyboard events to keep track of the number of characters. Ctrl+V is a single keypress (or two maybe), but it can cause your text to grow megabytes. :) You could use these events to update a label with the current number of characters.
不要使用键盘事件来跟踪字符数。Ctrl+V 是一个单一的按键(或两个),但它可能会导致您的文本增长兆字节。:) 您可以使用这些事件来更新具有当前字符数的标签。
Apart from onkeyup
, you can also use the oninput
event, which is triggered when you type into an input box.
除了onkeyup
,您还可以使用在oninput
输入框中键入内容时触发的事件。
And remember, always check on the server as well. Javascript may fail or can be deliberately disabled. Your server should always perform necessary checks. Although I believe that MySQL will automatically truncate texts that are too large...
请记住,还要始终检查服务器。Javascript 可能会失败或被故意禁用。您的服务器应始终执行必要的检查。虽然我相信 MySQL 会自动截断过大的文本......
A good alternative would be to set the maxlength property of the inputs. This way, the maximum length is enforced even without javascript. Then, you can remove that flag and add the necessary events from javascript. This way, you will have a usable solution for javascript browsers, while having a more strict check for non-javascript browsers, which I think is better than no check at all.
一个不错的选择是设置输入的 maxlength 属性。这样,即使没有 javascript,也会强制执行最大长度。然后,您可以删除该标志并从 javascript 添加必要的事件。这样,您将有一个适用于 javascript 浏览器的可用解决方案,同时对非 javascript 浏览器进行更严格的检查,我认为这比根本不检查要好。
回答by Naftali aka Neal
HTML:
HTML:
<input type='text' id='text'/>
JS:
JS:
function textLength(value){
var maxLength = 144;
if(value.length > maxLength) return false;
return true;
}
document.getElementById('text').onkeyup = function(){
if(!textLength(this.value)) alert('text is too long!');
}
Here is a fiddle demo: http://jsfiddle.net/maniator/L2LRK/
这是一个小提琴演示:http: //jsfiddle.net/maniator/L2LRK/
回答by TommyDo
I found the bug in your suggestion. Here my test patterns:
我在你的建议中发现了错误。这是我的测试模式:
If limit max characters are 05characters. Test value: 123456, ABCDEF
如果限制最大字符为05 个字符。测试值:123456,ABCDEF
1: Use keyboard, type the text normally
1:使用键盘,正常输入文字
for 123456, 6 will be deleted
对于 123456,将删除 6 个
for ABCDEF, F will be deleted
对于 ABCDEF,F 将被删除
Result: OK
结果:好的
2: Use keyboard, copy and paste 123456 and ABCDEF from other place
2:使用键盘,从其他地方复制粘贴123456和ABCDEF
for 123456, paste (Ctrl V): "123456123456" => 456123456 will be deleted
对于 123456,粘贴 (Ctrl V): "123456123456" => 456123456 将被删除
for ABCDEF, paste (Ctrl V): "ABCDEFABCDEF" => DEFABCDEF will be deleted
对于 ABCDEF,粘贴 (Ctrl V): "ABCDEFABCDEF" => DEFABCDEF 将被删除
Result: OK
结果:好的
3: Use mouse, copy and paste 123456 and ABCDEF from other place
3:使用鼠标,从其他地方复制粘贴123456和ABCDEF
for 123456, paste (Right click + paste): "123456123456" => NO characters will be deleted
对于 123456,粘贴(右键单击 + 粘贴):“123456123456” => 不会删除任何字符
for ABCDEF, paste (Right click + paste): "ABCDEFABCDEF" => NO characters will be deleted
对于 ABCDEF,粘贴(右键单击 + 粘贴):“ABCDEFABCDEF” => 不会删除任何字符
Result: FALSE;
结果:错误;
4: Use mouse, copy and paste 123456 and ABCDEF from other place after that type something else
4:使用鼠标,从其他地方复制并粘贴123456和ABCDEF,然后输入其他内容
for 123456, paste (Right click + paste): "123456123456" => NO characters will be deleted, type "123" using keyboard => All text will be deleted.
对于 123456,粘贴(右键单击 + 粘贴):“123456123456”=> 不会删除任何字符,使用键盘输入“123”=> 将删除所有文本。
for ABCDEF, paste (Right click + paste): "ABCDEFABCDEF" => NO characters will be deleted, type "ABC" using keyboard => All text will be deleted.
对于 ABCDEF,粘贴(右键单击 + 粘贴):“ABCDEFABCDEF”=> 不会删除任何字符,使用键盘输入“ABC”=> 将删除所有文本。
Result: FALSE;
结果:错误;
I give you my false from my project at same function. In my function this pattern are false for ALL. Here my : jsfiddleThis function that I have found in the internet, sorry I forget the source so If you are the owner, please for give me to public here.
我从我的项目中以相同的功能给你我的假。在我的函数中,这种模式对所有人来说都是错误的。这里是我的:jsfiddle这个功能是我在网上找到的,抱歉忘了出处,所以如果你是楼主,请把我在这里公之于众。
HTML:
HTML:
//Count content
maxL = 2000;
var bName = navigator.appName;
function taLimit(taObj) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
} else {
objCnt.innerText = maxL - objVal.length;
}
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
} //End Count content
You have <b><label id="myCounter">2000</label></b> characters left
<br/>
<textarea class="inputtextfield" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" id="content" name="content" rows=7 wrap="physical" cols=40></textarea>
I am very confused how to fix my bug.
我很困惑如何修复我的错误。
回答by amosrivera
There are two functions because there are two different events. If you wanted to know when someone pressed Ctrl + Enter
for instance you need to know exactly when each key is hold down and when it is released.
因为有两个不同的事件,所以有两个函数。例如,如果您想知道某人何时按下Ctrl + Enter
,您需要确切地知道每个键何时被按下以及何时被释放。
In your case (display a warning when reached the limit) i would use keydown
because that is what happens first, that way you know right at the moment when the user went over X characters. If you used keyup
te user could press a key for several seconds without seeing any message.
在您的情况下(达到限制时显示警告)我会使用,keydown
因为这是最先发生的事情,这样您就知道在用户超过 X 个字符的那一刻。如果您使用keyup
te 用户可能会按下一个键几秒钟而不会看到任何消息。
To count the characters you can do:
要计算您可以执行的字符数:
document.getElementById("myInput").value.length