javascriptjqueryautocomplete

Loop through <select> and build array in the format: "value1","value2","value3"


I wonder if anyone could suggest the best way of looping through all the <option> s in a <select> element with jQuery, and building an array.

Eg.

Instead of the following, whereby a string ins passed to the autoCompleteArray(),

$("#CityLocal").autocompleteArray(
        [
            "Aberdeen", "Ada", "Adamsville", "Zoar" //and a million other cities...
        ],
        {
            delay:10,
            minChars:1,
            matchSubset:1,
            onItemSelect:selectItem,
            onFindValue:findValue,
            autoFill:true,
            maxItemsToShow:10
        }
    );

...I need to loop through all the <options> in a <select> and push them into an array, and just pass that array variable to the function instead of a long string.

Eg,

$("#CityLocal").autocompleteArray(
            [
                MyBigArrayOfOptions
            ],
            {
                delay:10,
                minChars:1,
                matchSubset:1,
                onItemSelect:selectItem,
                onFindValue:findValue,
                autoFill:true,
                maxItemsToShow:10
            }
        );

I'd be grateful if you could suggest how to push stuff into an array in the correct format. I've pretty much sussed the looping part from another post on this site.

Thanks.


Solution

  • This should work:

    $(document).ready(function(){
      // array of option elements' values
      var optionValues = [];
      // array of option elements' text
      var optionTexts = [];
    
      // iterate through all option elements
      $('#sel > option').each(function() {
        // get value/text and push it into respective array
        optionValues.push($(this).val());
        optionTexts.push($(this).text());
      });
    
      // test with alert
      alert(optionValues);
      alert(optionTexts);
    });
    

    Given that your select element has ID sel.