Friday, March 6

Best way to add options to a select from an array with jQuery

 
This is slightly faster and cleaner.
 
And it's better idea to cache ' $('#mySelect') ' , so 
that you look up only once before the loop. Currently it is searching 
the DOM for the element for every single option .
  
<script>

    selectValues = { "1": "test 1", "2": "test 2" };
   
    jQuery.each(selectValues, function(key, value) {
        $('#mySelect').append(jQuery("<option/>", {
            value: key,
            text: value
        }));
    });

</script>

No comments:

Post a Comment