I’m currently stuck in trying to render different images in the user’s view based of radio button selection. I’m able to manipulate the image if I hard code selections, but I cannot find how to pass the user’s selection from JQuery to Rails.
First my view with the radio buttons is like so:
<!-- VIEW CODE -->
<% [ 'credit_32.png', 'credit_64.png' ].each do |image| %>
<%= radio_button_tag 'image', image, @image == image, :class => 'image' %><%= image_tag(image)%>
<% end %>
I then have a div that I’m trying to update with either of the images based off selection, my function to change, in a javascript file I listen for this on the click event:
// Javascript Asset File
$(function() {
$("input.image").live("click", function() {
$image = ($(this).val());
$.getScript( this.href );
});
});
This sets the user’s selection to the $image variable, and calls the index.js.erb code which will then rerender a partial.
// Index.js.erb for responding to
$("div#button").html("<%= escape_javascript(render(@button)) %>");
The problem I’m having is how do I get my previous variable to my partial?
<!-- Partial Code -->
<% if @button_image = $image %>
<%= link_to image_tag(@button_image), button_path(button, :only_path => false), :target => '_blank' %>
<% else %>
<%= link_to image_tag('credit_32.png'), button_path(button, :only_path => false), :target => '_blank' %>
<% end %>
If I could set this @button_image instance variable to my JQuery $image object, I’d be good, though I do not know if this is possible? Could I possibly save the JQuery object into a session and use it here? Thank you
the
$.getScript()method is only a shorthand for the$.ajax()method (link: http://api.jquery.com/jQuery.getScript/)you could just use the normal
$.ajax()method with adataattribute. eg:now in rails you can access it with the
paramshash.more info: http://api.jquery.com/jQuery.ajax/