2

I have this input field in Rails 3.1:

<%=f.file_field :image, :id => "upload"%>

I want to add this JavaScript before the input field:

onchange="readURL(this);

How can I do this?

Must see in HTML sth like:

<input type="file" onchange="readURL(this); name="post[image]" id="upload">

2 Answers 2

2

Are you using JQuery?

$("#upload").change(function() { 
  ..
}); 

is one way and

$("#upload").bind("change", function() {
  ..
}); 

is another.

JQuery Doc.

Update:

You can write it as:

<%= f.file_field :image, :id => "upload", :onchange => "readURL(this)" %>

This will give you HTML something like:

<input type="file" onchange="readURL(this); return false;" name="post[image]" id="upload">
Sign up to request clarification or add additional context in comments.

1 Comment

its good, but how can I add onchange="readURL(this); inside jquery code? Thank you
0

The preferred way to do this is via unobtrusive JavaScript (essentially adding JavaScript functionality to a page after the DOM is loaded, and making it optional). In rails 3.1 and later, you want to add the JS code in Syed's answer to app/assets/javascript/controller_name.js.coffee or similiar.

1 Comment

Thank you Kyle I will do with unobtrusive Javascript :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.