Kleber Shimabuku 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:
<p class="fields">
<%= 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 <select> 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:
<h1>Users#new</h1>
<p>Find me in app/views/users/new.html.erb</p>
<div id="target_div">Hello world</div>
<select id="my_select">
<option value="mars">mars</option>
<option value="venus">venus</option>
</select>
See any js in there?? Okay, I used prototype. Here it is with jquery:
<h1>Users#new</h1>
<p>Find me in app/views/users/new.html.erb</p>
<div id="target_div">Hello world</div>
<%= 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:
<!DOCTYPE html>
<html>
<head>
<title><%= @title %></title>
<%= csrf_meta_tag %>
<%=
javascript_include_tag
"http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js",
"jquery.rails.js"
%>
<script type="text/javascript">
$(document).ready(function () {
$("#my_select").change(
function () {
var choice = $(this).val();
//turn 'this', which is the select element,
//into a JQuery collection object, which
//has a val() method.
var query_string = "select_val=" + choice + "&another_val=10";
$("#target_div").load('users/get_info', query_string)
}
);
});
</script>
</head>
<body>
<%= yield %>
</body>
</html>