Count characters in field dynamically

谁说胖子不能爱 提交于 2019-12-22 11:14:09

问题


I would like to count characters in a form textarea field dynamically, I know there is a similar question about this but I am wondering if it can count from a certain number towards 0, as example while writing a tweet on Twitter.

This code could be in javascript, PHP, it doesn't really matter to me.


回答1:


This should help you out. Here is a tutorial regarding usage - a demo is found below:

Usage:

<input name="text" onKeyDown="CountLeft(this.form.text, this.form.left,50);"
                   onKeyUp="CountLeft(this.form.text,this.form.left,50);">

Javascript:

<SCRIPT LANGUAGE="JavaScript">

 function CountLeft(field, count, max) 
 {
     if (field.value.length > max)
         field.value = field.value.substring(0, max);
     else
         count.value = max - field.value.length;
 }

</SCRIPT>

Demo - Credit to www.reconn.us

Hope this helps.




回答2:


With Javascript, use the KeyUp event handler, and check for the legnth-property on your text field on every event.

Example: http://jsfiddle.net/nslr/C2CNS/



来源:https://stackoverflow.com/questions/5379116/count-characters-in-field-dynamically

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