13

I tried applying the :maxlenght => 40 on a textarea on my form. But it didn't work out. Can we have a length limit on a textarea?

The code for text area is

<%= f.text_area :data,
                :rows => 2,
                :cols => 60 ,
                :maxlength => 140,
                :autocomplete => :off,
                :class => "textareabytes" %>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123

4 Answers4

13

Just like Rahul said, there's no maxlength attribute for textarea in HTML. Only text input's have that.

The thing you need to remember, is that RoR's text_area function (and all of RoR's HTML-generator functions) accept any argument you'll give them. If they don't recognized the parameter, then the'll just convert it to HTML.

<%=f.text_area :data, :hellothere => "hello to you too"%>

Will output this HTML:

<textarea name="data" hellothere="hello to you too"></textarea>

I know it's hard to remember, but Ruby on Rails isn't magic, it just does a lot of things for you. The trick is to know how it does them, so you can understand why they work, and how to fix them when they don't!

Community
  • 1
  • 1
Shalom Craimer
  • 18,411
  • 8
  • 66
  • 100
  • 5
    There is a `maxlength` attribute for `textarea`since HTML5. Unfortunately, it is not supported in IE prior to 10. See MDN for [full details](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea). – ronan_mac May 12 '14 at 20:19
  • 1
    +1 for "I know It's hard to remember, but Ruby on Rails isn't magic-" – 0112 Sep 15 '14 at 15:35
  • 2
    Sources on maxlength for HTML5: http://www.w3schools.com/tags/att_textarea_maxlength.asp https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#Attributes – 0112 Sep 15 '14 at 15:44
  • I don't understand. According to what you say, the `` should be there then. Because once it is there on the client side, it works (at least in latest Chrome). But in my case it is not rendered. – Augustin Riedinger Oct 14 '14 at 12:39
4

Could it be due to a typo?

":maxlenght => 40 " in your post is misspelt.

EDIT:

I didn't read your post carefully. I think there is no maxlength attribute for textarea in HTML. You will have to handle it in JavaScript. There is more information in "MaxLength on a Textarea".

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rahul
  • 12,392
  • 13
  • 55
  • 59
  • Im sorry actually Its correct in the code i spelt it wrong here –  May 20 '09 at 05:59
  • Thnx buddy since no other go .....i wrote a javascript function to implement this.... –  May 20 '09 at 06:57
0

Not strictly what you're after of course, but, you can always put a:

validates_length_of :data, max: 40

on your model. Won't stop the textarea size of course :)

patrickdavey
  • 1,786
  • 2
  • 17
  • 21
0

You can use the maxlength attribute. It is new for the tag in HTML5. It should work nowadays.

konyak
  • 8,200
  • 3
  • 48
  • 59