Limits the number of characters in textarea, for Rails by Javascript
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)
{
va开发者_高级运维r 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!
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
You can decode it to ascii and check the length.
精彩评论