jQuery has a utility called $.inArray(value,array) . You can do something like this:
var array = [1,2,4]; $('#example option').each(function() { var $th = $(this); var value = parseInt($th.val()); if( $.inArray(value,array) >= 0 ) { $th.attr('selected','selected'); } });
$.inArray() returns the index of the value if it is found, or -1 if it is not in the array. This is why you need to test >= 0 .
See an example here -
http://jsfiddle.net/PJs37/
source share