Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
{
      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!

like image 742
ohho Avatar asked Dec 22 '22 16:12

ohho


1 Answers

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

like image 156
Kyle Macey Avatar answered Dec 24 '22 05:12

Kyle Macey