Kleber S. wrote in post #1016065:
@7stud,
the “onchange” behavior make a function call, that’s right, and this
function (load_part_price_select() ) belongs to a js file, in this
case I did put it on the application.js file.
Yeah, but you put the js that calls the function in the html here:
<%= f.collection_select(:part_id, @parts, :id, :title, { :prompt =>
true } , { :onchange => "load_part_price_select(this.id,
this.options[this.selectedIndex].value);" } ) %>
<%= f.label(:part_id, "Price: ") %>
Doesn’t that look like a bunch of chicken scratchings to you? You could
make it ‘look’ better with some spacing, but the point is: mixing html
and javascript is bad style. If you load that page in a browser and do a
View Source, and then look at the tag, it will have an onchange
attribute.
Mixing html and js was considered bad style more than 7 years ago, and
it remains bad style today. In fact, Rails 3 was redesigned so that
when rails generates html pages, no js appears in the html pages. In
your case, you are writing your own js(using jQuery), and you just
foiled the rails teams hard work by explicitly writing your js in the
html. You should watch this:
this is actually working for me.
Yes. It’s horrible style though. css, js, and html should all be in
separate files. If you examine the code I posted, this is what the html
looks like:
Users#new
Find me in app/views/users/new.html.erb
Hello world
mars
venus
See any js in there?? Okay, I used prototype. Here it is with jquery:
Users#new
Find me in app/views/users/new.html.erb
Hello world
<%= form_for(@user) do |f|
f.collection_select(
:id,
@users,
:id,
:email,
{ :prompt => true },
{
:id => “my_select”,
:class => “cool_effects”
}
)
end
%>
===app/views/layouts/application.html.erb:
<%= @title %>
<%= csrf_meta_tag %>
<%=
javascript_include_tag
"http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js",
"jquery.rails.js"
%>
<%= yield %>
===
class UsersController < ApplicationController
def new
@user = User.new
@users = User.find(:all)
@title = “Sign up”
end
def get_info
choice = params[:select_val].to_i
other_data = params[:another_val].to_i
reply = “Hello #{choice + other_data}”
render :text => reply
end
end
===
As far as I can tell, I need the route:
resources :users
in order for collection_select to work–in addition to:
get ‘users/get_info’
for the ajax request.