Maximum length on a textarea in Ruby on Rails
Asked Answered
B

4

14

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" %>
Brusquerie answered 20/5, 2009 at 5:50 Comment(0)
M
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!

Mascagni answered 20/5, 2009 at 6:38 Comment(4)
There is a maxlength attribute for textareasince HTML5. Unfortunately, it is not supported in IE prior to 10. See MDN for full details.Ragsdale
+1 for "I know It's hard to remember, but Ruby on Rails isn't magic-"Misjoinder
Sources on maxlength for HTML5: w3schools.com/tags/att_textarea_maxlength.asp developer.mozilla.org/en-US/docs/Web/HTML/Element/…Misjoinder
I don't understand. According to what you say, the <textarea maxlength="50"></textarea> 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.Hannigan
B
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".

Burnside answered 20/5, 2009 at 5:54 Comment(2)
Im sorry actually Its correct in the code i spelt it wrong hereBrusquerie
Thnx buddy since no other go .....i wrote a javascript function to implement this....Brusquerie
C
1

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 :)

Cutwork answered 10/4, 2015 at 4:45 Comment(1)
Right approach even using maxlength tag.Bouffant
C
1

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

Citrin answered 16/10, 2019 at 15:47 Comment(1)
You right! It works as well in Firefox, Chrome and Opera on Ubuntu in 2021! \o/Bouffant

© 2022 - 2024 — McMap. All rights reserved.