You can use unobtrusive jQuery and a data-attribute.
For example in my app I have a big form with, among the others, an "address" fieldset in which the user should:
- write his address and then
- hit a "check" button to display a little google map to see if the address he entered is correct.
Of couse after he its the "check" button I want to render the form again but with the ancor to this address fieldset, where the map is displayed.
This is my .erb template:
<fieldset id="address" data-preview="<%= params[:preview] ? true : false -%>">
<legend>Write you address here, then check it</legend>
<div class="field">
<%= f.text_field :address %>
<input id="preview-button" type="submit" name="preview" value="check">
</div>
</fieldset>
When the check button is hit, it will set params[:preview]. In my controller, the create action looks like this:
def create
@obj = current_user.objs.new(params[:obj])
if params[:preview]
# geocoding code, and then:
render action: "edit"
else
#...
end
end
So the action edit will be rendered with params[:preview] still defined, and this will set the #address fieldset data-preview to true. Namely, this line of HTML will be rendered:
<fieldset id="address" data-preview="true">
Now all I need to do is to fetch that information through javascript and if data-preview is true move window location to the #address anchor. Here is my unobtrusive jQuery code:
$(function() {
var preview = $("#address").data('preview');
if (preview == true){
window.location = window.location.href + "#address";
};
});
And that's it!
answered 2012-09-24T11:13:43.223