Wednesday, June 9, 2010

Form with Multiple-selection Select Stored in Rails Comma-delimited Model Attribute

Here is an example for how you can do multiple-selections in a Rails form and store as a comma-delimited single field. This solution is based off of the one by smallbeer and Bill Posters, but in addition it sets the selections.

<p>
  <script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>  
  <script>
$.noConflict();
 jQuery(document).ready(function($) {

  function setHandlers(e) {
   $('select[id^=select_favorite_foods]').change(updateValue);
  }

  function updateValue() {
   var select_values = [];
   $('select[id^=select_favorite_foods]').each(function(e) {
    if ($(this).val()) select_values.push($(this).val());
   });
   $('#name_of_your_model_favorite_foods').val(select_values.join(','));
  }
  
  function initSelection() {
    vals = $('#name_of_your_model_favorite_foods').val().split(',');
    var select_values = [];
    for ( i = 0; i < vals.length; i++) {
      if (vals[i]) select_values.push(vals[i]);
    }
    $('select[id^=select_favorite_foods]').val(select_values);
  }

  $(document).ready(function() {
   initSelection();
   setHandlers();
   updateValue(); 
  });
 });
  </script>
  <%= f.label :favorite_foods, "Select your favorite foods:" %><br />
  <%= f.hidden_field :favorite_foods %>
  <select id="select_favorite_foods" multiple="true" size="3">
    <option value="Orange">Orange</option>
    <option value="Banana">Banana</option>
    <option value="Grapefruit">Grapefruit</option>
  </select>
</p>

Messy, but it is just an example! However, for Rails, if you don't mind storing the value in the DB as YAML, that is a little easier. Also, this same technique with a few mods could work for any HTML form.

(Thanks to Jeremy who provided ideas when I was trying to work through the initSelection method.)

No comments: