What I want to do is to generate option elements for a multiple select drop-down from a JavaScript array. Than select each option in the drop-down that is the same as the value in another array (The results array in the example).
The problem is that when the results array has multiple elements, the original options get multiplied in the HTML for the number of elements in the results array.
I understand why this is happening, but I cant seem to find a better solution then the one I currently use, which is something like this:
var
options = ['Some value', 'Another value', 'Third value', 'Something completely different'],
results = ['Some value', 'Another value'],
selectHtml;
$.each( options, function( index, value ) {
var option = value;
$.each( results, function( index, value ) {
if ( option === value ) {
selectHtml += '<option selected="selected" value="' + option + '">' + option + '</option>';
}
else {
selectHtml += '<option value="' + option + '">' + option + '</option>';
}
});
});
You can find a live example here: http://jsfiddle.net/wCWyp/
What I want to accomplish is the same thing, but without the multiplication of the elements.