Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created March 5, 2010 21:22
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nakajima/323166 to your computer and use it in GitHub Desktop.
Choose an option from a select by text
// 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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment