2008-10-23 84 views
4

我不知道是否有人可以建议使用jQuery遍历所有<option>元素在<select>元素中的最佳方式,并构建一个阵列。循环通过<select>并建立数组格式:“value1”,“value2”,“value3”

例如,

相反以下,由此串插件传递给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 
     } 
    ); 

...我需要遍历所有<options><select>并将它们推到一个数组,只是将该数组变量传递给函数而不是长字符串。

例如,

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

我会很感激,如果你能建议如何推动东西到正确的格式的数组。我非常怀疑这个网站上另一篇文章的循环部分。

谢谢。

回答

8

这应该工作:

$(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); 
}); 

鉴于您select元素有ID SEL

+0

你如何只选定的项目筛选该? – 2009-07-23 12:59:56

+0

在`.each`循环中: if(this.selected){code for push } – 2009-07-24 15:39:11

6

jQuery.map函数可能是你正在寻找的。下面的代码将创建一个数组,其中包含<select>选项的所有值或文本值。

var values = jQuery.map(jQuery("#select")[0].options, function(option) 
      { 
       return option.value; 
      }); 

var texts = jQuery.map(jQuery("#select")[0].options, function(option) 
      { 
       return option.innerHTML; 
      }); 
2

所有你需要做的是传递数组作为第一个参数没有括号。括号创建一个新的数组,但你不需要这样做,因为你已经传递了一个数组。只要做到:

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

如果我明白你的问题corrently,下面的代码应该做你需要的东西:

myFunction($("#my-select option")); 

查询的输出已经是属于选择的后代选项数组,所以你不需要将它们推入另一个数组中。另外,如果你的选择没有一个id,但是你的DOM元素:

myFunction($("option", theSelect)); 

堵这个想法回到你的代码:

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