Populating Select Boxes with Prototype

Adding removing options from drop downs can be down right annoying, but I came up with a simple prototype function that I think makes it a lot easier.

You just pass your select box object, an object with an enumerable-esque ‘each’ method, and a method for creating the individual options. On the advice of my wonderful co-worker Jim, you can pass an optional 4th argument that lets you maintain the options length. It’s defaulted to 1 in order to preserve the first element in a drop down, which we typically leave blank.

Here’s the function:

// Requires Prototype: http://www.prototypejs.org/
function setDropDown(field, data, method, index) {
  field.options.length = index == null ? 1 : index;
  data.each(
    function(e) {
      field.options.add(method(e));
    }
  );
}

And here are some quick examples:

To clear a drop down:

setDropDown(selectBoxObject,[]);

To copy items from one drop down to another:

setDropDown(
  selectBoxObject,
  otherSelectBoxObject.options,
  function(e) {
    return new Option(e.text, e.value);
  }
);

Quick example using JSON

var json = Object.toJSON( {"COUNTRIES":[{"COUNTRY":"Hong Kong","ID":1},{"COUNTRY":"Japan","ID":2}]} );

setDropDown(
  selectBoxObject,
  json.COUNTRIES,
  function(e) {
    return new Option( e.COUNTRY, e.ID );
  }
);