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.

  <script src="" type="text/javascript"></script>  
 jQuery(document).ready(function($) {

  function setHandlers(e) {

  function updateValue() {
   var select_values = [];
   $('select[id^=select_favorite_foods]').each(function(e) {
    if ($(this).val()) select_values.push($(this).val());
  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]);

  $(document).ready(function() {
  <%= 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>

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: