开发者

Autocomplete problem with two identical "values"

开发者 https://www.devze.com 2023-03-09 01:53 出处:网络
I\'m using the JQuery Autocomplete plugin, with local data stored in a array: data = [city1, city2, city3, city1]

I'm using the JQuery Autocomplete plugin, with local data stored in a array:

data = [city1, city2, city3, city1]

Once the user selects the data element, for example city 1, I store it in user_input. I use the user input to read a hash that contains city, state zip, and name. The script displays each element of the hash on screen when the user hits enter. This also works great:

  $(document).keypress(function(e) {
      if(e.keyCode == 13) {
          var user_input =  $("input#example").val()

            $.each(personinfo,function(key,value){
                if(value['city']== user_input){
                    $('#city').empty().append(value['city']);
                    $('#state').empty().append(value['state']);
                    $('#zip').empty().append(value['zip']);
                    $('#name').empty().append(value['name']);
                }
})

The problem arises when there are two identical keys. For instance, say a name "John Doe" and "Jane Doe", live in the same city: city1. Therefore city1 appears twice in the data array, as you see above.

data is defined in this method:

  var data = new Array();
  $(document).ready(function(){

  $.each(personinfo,function(key,value){
    myarray.push(value['city'])
   });
  });

How can I differentiate amongst city1 and city1 in the above array within the keypress function?

The personinfo map object:

开发者_StackOverflow中文版{"address":"07288 Albertha Station","city":"Littelside","created_at":"2011-05-25T19:24:51Z","id":1,"name":"Jane Doe","state":"Missouri","updated_at":"2011-05-26T21:25:54Z","zip":"75475-9938"},{OBJECT 2}, {OBJECT 3}, .... 


As some of the comments suggest, it's impossible to fix a problem with identical keys: the only way to fix it is to use non-identical keys :-)

I'd just combine city and state to make the key; seems like that should give you a unique keyset.


It's probably late now, but I just had to fix this problem in a similar plugin and the best way of doing it is to pass additional reference with the lookup data.

As in lookup = { data: ['name1', 'name2', 'name2', 'namex'], ref:[1,2,3,4] }

So that when user selects second 'name2' the plugin will return selected 'name2' and ref 3. It depends on a plugin if it supports this functionality, but even if it doesn't you should be able to modify it slighlty.

0

精彩评论

暂无评论...
验证码 换一张
取 消