Max
Max

Reputation: 57

Ruby on Rails Send form information to Javascript script

This shouldn't be a difficult problem to answer, but I can't find my answer from searching google.

I'm trying to have a form that tells me how many characters you have remaining. I got the code working in basic html, but I'm having difficulty converting it into rails.

In html, the relevent piece of code looks like:

<textarea name="content" onKeyUp="rem_char(this.form.content);"></textarea>

In Rails, the code looks like:

<%= f.text_area :content, :onkeyup => "rem_char(this.form.content);" %>

I can tell from viewing the source of the Rails document that the name of textarea is "micropost[content]", but changing "this.form.micropost[content]" does not work. In addition, adding :name => "content", causes the form input to not be read.

Upvotes: 0

Views: 343

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

<%= f.text_area :content, :onkeyup => "rem_char(this);" %>

When that JS runs, this is the textarea. You then ask for the textarea's form, then ask the form for the element named content, which is the textarea. So save yourself the name dependent roundtrip there entirely, and just use this.


Alternatively, use id, not name.

<%= f.text_area :content, 
      :onkeyup => "rem_char(document.getElementById('micropost_content'));" %>

Upvotes: 1

Related Questions