There is jQuery script in view. Script operates OK when the page is opened first time and data is put from server for view without AJAX. When I choose item from drop-down list, AJAX send it to controller. Controller render *.js.erb view and *.html.erb view shows info correctly for the last time. Since now it looks like script disappear from the view (from the page). No any reaction on choosing of the item from drop-down list.
But if I copy this script from *.html.erb view to *.js.erb view, everithing operates OK always.
I can not understand this behaviour. With AJAX I only change info in one div in view and do not touch script section of this view…
Action in values_controller.rb
@values = Value.all
# This value initially generates here and next time goes from view with AJAX
@chosen_value = if params[:chosen_value].present?
Value.find_by(label: params[:chosen_value])
else
'Just_label_of_my_value'
end
respond_to do |format|
format.js
format.html { render 'value_shows' }
end
value_shows.html.erb
<div>
<%= select("label", "label_value", @values.collect { |c| [ c[:name], c[:name] ] }, { prompt: '[Choose label]'}) %>
</div>
<div id="graphs">
<%= @chosen_value %>
</div>
<script>
$(function(){
if (!$('#label_label_value').val()) {
$('#label_label_value').val('<%= @chosen_value %>')
}
$("#label_label_value").change(function() {
$.ajax({ url: "/value_action", data: { 'chosen_value' : $('#label_label_value').val() }});
});
});
</script>
value_shows.js.erb
$("#graphs").html("<%= escape_javascript(render :partial => 'graphics') %>");
// If I copy script from view to here, everithing operates ok:
$(function(){
if (!$('#label_label_value').val()) {
$('#label_label_value').val('<%= @chosen_value %>')
}
$("#label_label_value").change(function() {
$.ajax({ url: "/value_shows", data: { 'chosen_value' : $('#label_label_value').val() }});
});
});
_graphics.html.erb
<%= @chosen_value %>
route
get 'value_shows' => 'values#value_shows', as: :value_shows