jxson
3/8/2010 - 8:47 PM

I choo choo choose you.js

// Usage:
//
//  $('#the-select').choose('Some Option');
//
// It'll throw an error if the option doesn't exist.
$.fn.choose = function(name) {
  var elem = $(this);
  if (elem.is(':not(select)')) { return elem; }

  var option = elem.find('option').filter(function() {
    return name == $.trim($(this).text());
  });

  if (option.size()) {
    option.attr('selected', 'selected');
  } else {
    throw(new Error(name + ' is not a valid option!'));
  }

  return elem;
};