I ran into this question and was not satisfied with the answers. Here is a generic, non-jQuery version. It uses Array.indexOf
where possible, but returns to the foreach loop if it is not available.
Pass a node to the function along with an array of values. Throws an exception if an invalid element is passed to it. To do this, use ===
to check the value. For the most part, make sure you compare the value of the parameter with an array of strings.
eg. selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );
var selectValues = (function() { var inArray = ( function() { var returnFn; if( typeof Array.prototype.indexOf === "function" ) { returnFn = function(option, values) { return values.indexOf( option.value ) !== -1; }; } else { returnFn = function(option, values) { var i; for( i = 0; i < values.length; i += 1 ) { if( values[ i ] === option.value ) { return true; } } return false; } } return returnFn; }() ); return function selectValues(elem, values) { var i, option; if( typeof elem !== "object" || typeof elem.nodeType === "undefined" ) throw 'selectValues() expects a DOM Node as it\ first parameter, ' + ( typeof elem ) + ' given.'; if( typeof elem.options === "undefined" ) throw 'selectValues() expects a <select> node with options as it\ first parameter.'; for( i = 0; i < elem.options.length; i += 1 ) { option = elem.options[ i ]; option.selected = inArray( option, values ); } } }());
source share