I have a list of items loaded into a radio button list. When one of those items is clicked, I want to display additional information about that item in a div elsewhere on the page. For example, I am listing different types of rooms for a hotel. If the user clicks on a particular room type, I want to display the estimated cost of that room in a different diff.
After much googling about, I came across this post: Rails + Radio Buttons + AJAX: How to render partial on radio button click? . It gave me the idea to use partials; however the answer didn't quite provide enough guidance for me so I did a little reading on partials. I ended up with the following:
In my main view
<% @available_rooms.each do |rt| %>
<div class="radio-item">
<%= b.radio_button :room_type, rt.id, :class => 'rb_room_type inline', :onclick => 'render_room_info();' %>
<%= content_tag :span, rt.name %>
<a data-toggle="tooltip" data-placement="right" title="<%= rt.description %>">
<%= image_tag "tooltip.png", :class=>"tooltip-icon" %>
</a>
</div>
<% end %>
<div id="estimated-due" class="group column-2">
</div>
My partial view named _room_details.html.erb
<span class="booking-est-cost">Estimated Cost: £<%= rt.room_price %></span>
Javascript File
function render_room_info() {
$("#estimated-due").html("<%= j render :partial => 'room_details', locals => { :rt => @rt } %>");
}
From everything I've read, this should work. However, when I click on a radio button, it renders out the literal html string in the div:
<%= j render :partial => 'room_details', locals => { :rt => @rt } %>
So clearly the rails code isn't firing. Since javascript is client side, I guess this makes sense but I can't really figure out how to make this work. I read a few articles that talked about doing ajax requests but they all seemed like serious overkill for what I need to do (not to mention overly complex). Am I missing something simple? I just need to render out the value of one or two fields on click of a radio button.
Just as a reference, I'm using Rails 4.2.
You need to submit an ajax request to a rails route. Because you are doing this from a radio button, you could do something like:
function render_room_info() {
$.ajax({
url: room_rate?rt=xx,
dataType: "script"
});
}
Then the action at the route specified above needs to respond to a ajax request:
#some logic to get set the @rt variable
@rt = params[:rt]
respond_to do |format|
format.html {
}
format.js {
}
end
and then you put your instructions to replace with a partial in a js file based on the name of the controller action eg room_rate.js
$("#estimated-due").html("<%= j render :partial => 'room_details', locals => { :rt => @rt } %>");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.