Search code examples
jqueryruby-on-railscollectionssimple-form

How can I use jQuery to pull the ids from a multiple collection select?


I'm a hobbyist on my first project. If I've got this simpleform collection:

<%= f.input :events, collection: @organizer.events.order(:start_time).reverse, label_method: :event_name_and_date, input_html: {multiple: true, id: "event_select"} %>

How can I pull the event.id from the selected events, so I can dynamically update the rest of the ensuing form with the individual ids? Currently, if I grab the value of the collection, all the ids are combined in one long string. I don't know how to break them up and store them.

For example, I've got:

<script type="text/javascript">
  $(document).ready(function() {
    $('#event_select').on('change', function(){
        var grab_events = $('#event_select').val();
        $('#show_events').html(grab_events);    
    })
  });

</script>

But that just shows a string of all the ids, uselessly. Ids 43, 65, 32, and 8 come out as '4365328'


Solution

  • grab_events is an array. When using .html(), jQuery is inserting each element individually by looping, without invoking toString(). since newlines aren't relevant, looks like a long string. One solution is call toString() manually, or wrap the items in a block element.

    Of course, being an array you can do whatever you want with it later.

    $('#event_select').on('change', function() {
      var grab_events = $('#event_select').val();
    
      // Inserting array, resulting in one long string
      $('#show_events').html(grab_events);
      // Separate with commas
      $('#show_events2').html(grab_events.toString());
      // Create a div for each element
      $('#show_events3').html(grab_events.map(i => $(`<div>${i}</div>`)));
    
      grab_events.forEach(i => {
        // Whatever you want to do
      });
    })
    #show_events {
      background-color: red;
    }
    
    #show_events2 {
      background-color: green;
    }
    
    #show_events3 {
      background-color: yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="event_select" multiple="multiple">
      <option value="11">item 1</option>
      <option value="24">item 2</option>
      <option value="43">item 3</option>
      <option value="4">item 4</option>
      <option value="35">item 5</option>
      <option value="16">item 6</option>
    </select>
    <div id="show_events"></div>
    <div id="show_events2"></div>
    <div id="show_events3"></div>