Search code examples
jqueryruby-on-railsselecthidden-fieldcollection-select

Set Hidden Field Value Based on Collection_select select menu


I am using select2 and I have a collection_select in an update form that looks like this:

<%= collection_select(:event, :project_date_id, @project_dates.available, :id, :schedule_date, :prompt => false, :selected => @set_date.id)  %>

When an option is selected (:id), I want to also put the displayed value (:schedule_date) in a hidden field.

<%= f.hidden_field :starts_on, value: {HERE'S WHERE the :schedule_date display value from the select goes}



I feel like this is a job for Jquery...but I'm very new to Jquery and having trouble figuring it out.


Solution

  • I'm not ruby developer, but in case of jquery, you can do like this :

    <script>
      $(function(){
        $(document).on('change','#_id_name_for_select', function(){
           var select_value = $(this).val();
           $('#_id_name_for_hidden_field').val(select_value);
    
        });
      });
    </script>