How to binding a JS event to a field within form_for block

Dear all,

I’m new to Rails and Web development, I have a problem about how to
“bind a JS event to a field within form_for block”.

I have a JS function called checkLength, which is used to check the
length of words typed in a text area field:

HTML code with JS event invocation

Now I would like to reuse this JS funtion in another Rails view page,
which the src code is listed below:


<%= form_for @micropost do |f| %>

f.text_area :content

<% end %>

The question is after I put the JS function under RAILS_APP/public/
javascript as custom.js and include it with javascript_include_tag.

f_text_area :content AND CALL THE JS FUNCTION LIKE :
oninput=“checkLength(this, 5)”

Have you ever heard about unobstrusive javascript?

You write your html without any javascript, then you add the js behavior
that you want in a separeted file.

A simple search by “unobstrusive+javascript+” will
return a
lot of material to read about.

I apologize on behalf of pedro , the rails community is usually very
kind to
new comers.

Rails usually comes with a javascript library, the default is jquery, if
generate a scaffold you will see it gets imported in the head tag

<%= javascript_include_tag :defaults%>

will import it.

with it you can capture html element via a css selector and attach event
the element.

that is an old tutorial but it will get you started.

This is a very basic question, a simple google search and just a little
reading about like I said will light your way.

On Sun, Oct 23, 2011 at 12:53 PM, Pedro Fernandes Steimbruch <
[email protected]> wrote:

This is a very basic question, a simple google search and just a little
reading about like I said will light your way.

The web programming paradigm is very confusing for a beginner and the
rails makes things seem magical is even more confusing to some people, i
often find easier to teach rails and web developing to someone
new to programming.

The form helper could be very obscure is you dont really know what
are. Also some basic javascript tutorials still have embedded js and to
some the benefits of been unobtrusive are not obvious.

Pauls seem to be confused not by javascript but by the form helper and
way it renders html at the end so he does not appears to know that the
helper outputs an id form him to capture via js.

Hi Radhames,

Thank you so much for your kindly help and patient. I found the answer
by the link you point above.

As you said, the question it’s not about the JS itself but rather than
how to render JS in Rails ERB file. After read though the text_area
API, I got the answer.

Next time I will start from reading API instead of posting such a
native question. Thank you again

Hi Pedro,

Thank you for your suggestion and I found it help me a lot!