2
votes

In my Rails 3.2 app, I have something similar to an album page which shows many photos. Under each of the photos is a select box where the user can choose from a number of options, formatted something like this:

<select id="photo_1">
  <option value=value_1>Name of Value 1</option>
  ...
  <option value=value_n>Name of Value N</option>
</select>

The problem is, the list of values is very long (100s of possibilities), but exactly the same for each photo. Since each Album could possibly have dozens of photos, it seems inefficient to have the server send the full list each time a photo is loaded to the page. Is there a more efficient way to do this such as, for example, loading

  <option value=value_1>Name of Value 1</option>
  ...
  <option value=value_n>Name of Value N</option>

just once to the Album page when it is generated (perhaps as a hidden field), and then using jQuery/javascript to populate it into the photo's unique tags on the client side, when the photo is loaded to the page? (NOTE: Photos load dynamically, so some may load after the initial load of the Album page, as the user uploads them.)

2

2 Answers

1
votes

It would be better if the <select>s that require this had a common class, but this works for any <select> whose ID begins with photo (although you should probably use name rather than id).

$(function () {
    $("select[id^=photo]").each(function () {
       $(this).html($("#hidden_select").html());
    });
});​

JSFIDDLE

1
votes

You can just copy the options to the other elements

HTML

<select id="photo_1">
  <option value="value_">Pick</option>    
  <option value="value_1">Name of Value 1</option>
  <option value="value_2">Name of Value 2</option>
  <option value="value_3">Name of Value 3</option>
</select>
<select class="copy"></select>
<select class="copy"></select>

JavaScript

var mainSelectOptions = $("#photo_1 option").clone();
var selects = jQuery(".copy").append(mainSelectOptions);

Example: JSFiddle