Ask A Question

Notifications

You’re not receiving notifications from this thread.

Dynamic select boxes with Rails 4

JM asked in Javascript

Hey there I am trying out a dynamic select box with rails 4 and I am stuck on where to put the js code because the form exists in a nested form. So should the code go in the js file for the form accepting nested attributes or to the js file named as the partial of the data.

see my partial code below and js as well

_job_queue_fileds.html.erb

     <h4 style="text-align: center">Select Job Queue</h4><br>
           <div id="project_queue_id" class="field">
             <%= f.label :project_name %><br>
             <%= f.collection_select(:project_id, Project.order(:project_name), :id, :project_name, include_blank: true) %>
           </div><br>
           <div id="job_queue_id"class="field">
           <%= f.label :job_name %><br>
             <%= f.grouped_collection_select(:job_id, Project.order(:project_name), :jobs,  :project_name, :id, :job_name, include_blank: true) %>
           </div>

job_queues.js.coffee

  jQuery ->
    jobs = $('#job_queue_id').html()
    $('#project_queue_id').change ->
     project = $('#project_queue_id :selected').text()
       options = $(jobs).filter("optgroup[label='#{project}']").html
     if options
         $('#job_queue_id').html(options)
     else
       $('#job_queue_id').empty()

Will appreciate any pointers, I am not getting any errors but the data is not getting filtered as well

Reply

Hey John,

Any Javascript code you write inside the app/assets/javascripts folder gets included globally and is generally where you want to keep your code. It doesn't matter if you're using a regular form or a nested one, the JS won't care which is good for situations like this.

You might want to double check that you've got the right IDs for your fields because their names can change when you do nested forms. That is likely the reason that you're not getting any data filtered. Inspect the HTML on the page and make sure those form field ID's match up to your JS. With any luck, that hopefully fixes it!

Reply

Hi chris,

The issue is with how the form fields are added , I am using gem cocoon and they have an in built method to help sort that out ..

     cocoon:before-insert: called before inserting a new nested child
     cocoon:after-insert: called after inserting
     cocoon:before-remove: called before removing the nested child
     cocoon:after-remove: called after removal
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.