代码之家  ›  专栏  ›  技术社区  ›  jeffreyveon

自动完成jQuery插件:所选数组索引的值

  •  1
  • jeffreyveon  · 技术社区  · 15 年前

    如何获取数组中索引位置的值,用户使用autocomplete选择了哪个元素?

    例如,如果我输入两个元素作为autocomplete插件输入的数组:

    var arr = [];
    arr[0] = "John";
    arr[1] = "Paul";
    

    4 回复  |  直到 15 年前
        1
  •  0
  •   µBio    15 年前

    function FindIndex( arr, searchValue ){
        for( var i = 0; i < arr.length; ++i ){
            if( arr[i] === searchValue ){
                return i;
            }
         }
     }
    
        2
  •  1
  •   Alex Pakka    13 年前

    jQuery方式: 如果您的自动完成源是一个普通数组(即不是一个标签-值对或URL数组),那么您可以这样做

    $.inArray(ui.item.value,myAutocompleteSource)
    

    例如

           $('.my-autocompletes').autocomplete({
                      source:['Option1','Option2','Option3'],
                      select: function(event, ui) {
                        alert('Your selected a string with index '+
                         $.inArray(ui.item.value,$(_self).autocomplete('option','source'))
                        );
                  }
            });
    

    var index = -1;
    $(_self).autocomplete('option','source')).each(function(idx) { 
           if (this.label == ui.item.label) { index=idx; return false; }
    });
    alert('You selected a string with index '+index);
    

    当然 $(_self).autocomplete('option','source')) 可以替换为直接引用自动完成项的源。

        3
  •  0
  •   Cheeso    15 年前

    这个裁判 http://docs.jquery.com/Attributes/val#val

    $('#selection option:selected')....
    
        4
  •  0
  •   jitter    15 年前
    var arr = [];
    arr[0] = "John";
    arr[1] = "Paul";
    ...
    //user selects something
    //assuming select value now is in an input field
    var index = jQuery.inArray($("input#yourselector").val(), arr);
    if (index > -1)
        alert(index);
    else
        alert("value not found in autocomplete array");