Skip to content

Instantly share code, notes, and snippets.

@wolfravenous
Created September 20, 2016 13:09
Show Gist options
  • Save wolfravenous/9aaf0a052a5505e4e75fc98a74c8d83d to your computer and use it in GitHub Desktop.
Save wolfravenous/9aaf0a052a5505e4e75fc98a74c8d83d to your computer and use it in GitHub Desktop.
Strange behavior when setting up Dynamic Boxes using JQuery and SimpleForm. When I navigate to the page the first time, the dynamic selection does not work. If I refresh the page in the browser then the dynamic selector works. Here is a gist of the relevant code. I tried installing the gem jQuery TurboLinks as suggested by a stack overflow post …
<%= simple_form_for(report) do |f| %>
<%= f.association :subject %>
<%= f.input :intro_id, collection: Subject.all, as: :grouped_select, group_method: :intros %>
<%= f.input :unit_id, collection: Subject.all, as: :grouped_select, group_method: :units %>
<%= f.button :submit, class: "btn-primary" %>
<% end %>
//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
jQuery ->
intros = $('#report_intro_id').html()
$('#report_subject_id').change ->
subject = $('#report_subject_id :selected').text()
escaped_subject = subject.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(intros).filter("optgroup[label='#{escaped_subject}']").html()
if options
$('#report_intro_id').html(options)
else
$('#report_intro_id').empty()
units = $('#report_unit_id').html()
$('#report_subject_id').change ->
subject = $('#report_subject_id :selected').text()
escaped_subject = subject.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1')
options = $(units).filter("optgroup[label='#{escaped_subject}']").html()
if options
$('#report_unit_id').html(options)
else
$('#report_unit_id').empty()
@wolfravenous
Copy link
Author

Simple solution, specify the GET method in the link_to that is routing to the form with the jQuery dynamic select boxes.

<%= link_to "New Report", new_report_path, class: "new", method: :get %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment