通过Javascript限制Rails中textarea中的字符数(Limits the number of characters in textarea, for Rails by Javascript)

我想限制textarea的字符数。

我发现以下Javascript代码适用于纯HTML文件:

<script language="javascript" type="text/javascript"> function DjCheckMaxlength(oInObj) { var iMaxLen = parseInt(oInObj.getAttribute('maxlength')); var iCurLen = oInObj.value.length; if ( oInObj.getAttribute && iCurLen > iMaxLen ) { oInObj.value = oInObj.value.substring(0, iMaxLen); } } //@ END OF DjCheckMaxlength() </script> <body> <input type="text" name="T1" size="20" maxlength="20" > <br /><hr /> <textarea maxlength="10" onkeyup="return DjCheckMaxlength(this);"></textarea> </body>

在Rails应用程序中使用它的最佳方法是什么?

谢谢!

I'd like to limit the number of characters in textarea.

I found the following Javascript code works well for a plain HTML file:

<script language="javascript" type="text/javascript"> function DjCheckMaxlength(oInObj) { var iMaxLen = parseInt(oInObj.getAttribute('maxlength')); var iCurLen = oInObj.value.length; if ( oInObj.getAttribute && iCurLen > iMaxLen ) { oInObj.value = oInObj.value.substring(0, iMaxLen); } } //@ END OF DjCheckMaxlength() </script> <body> <input type="text" name="T1" size="20" maxlength="20" > <br /><hr /> <textarea maxlength="10" onkeyup="return DjCheckMaxlength(this);"></textarea> </body>

What's the best way to use it inside a Rails app?

Thanks!

最满意答案

应该工作基本相同。

<%= text_area 'comment', 'body', :onkeyup => "DjCheckMaxlength(this);", :maxlength => 30 %>

如果你想链接到外部:

<%= javascript_include_tag "my-functions" %>

会从public / javascripts / my-functions.js中获得一个JS文件

Should work essentially the same.

<%= text_area 'comment', 'body', :onkeyup => "DjCheckMaxlength(this);", :maxlength => 30 %>

If you want to link externally:

<%= javascript_include_tag "my-functions" %>

Would get a JS file from public/javascripts/my-functions.js

更多推荐