Setting the selected attr on an option is a bit trickier than what you might think at first because it effects other elements if the select element is of type 'select-one'. Here's a little plugin provided within the jQuery Form plugin that handles selecting/deselecting options as well as checkboxes and radios. Use it like this:
$('option.someClass').selected(true);
- /**
- * Select/deselect any matching checkboxes, radio buttons or option elements.
- */
- $.fn.selected = function(select) {
- if (select == undefined) select = true;
- return this.each(function() {
- var t = this.type;
- if (t == 'checkbox' || t == 'radio')
- this.checked = select;
- else if (this.tagName.toLowerCase() == 'option') {
- var $sel = $(this).parent('select');
- if (select && $sel[0] && $sel[0].type == 'select-one') {
- // deselect all other options
- $sel.find('option').selected(false);
- }
- this.selected = select;
- }
- });
- };