JQuery UI автозаполнение не ищет весь массив - PullRequest
0 голосов
/ 26 декабря 2018

Я использую функцию автозаполнения JQuery UI в html-файле.

Для автозаполнения необходимо проверить тип, спальни и расположение, которые я добавил в массив.Но проблема в том, что автозаполнение находит только тип второго объекта в массиве.

Как видите, у меня есть массив с именем properties, с двумя объектами, имеющими тип переменной.Но я могу искать только второй объект, а не оба.

Если кто-то может помочь, это будет высоко ценится.

Большое спасибо !!!

Ответы [ 2 ]

0 голосов
/ 26 декабря 2018

Если вы объявите свой массив внутри цикла, он будет сбрасываться в каждом цикле, и после выхода из цикла будет присутствовать только последняя переменная.

Я немного подправил код, и теперь онработает, как вы хотели бы.Я прокомментировал свои изменения.

Я добавил комментарии к вашему исходному коду ниже, объясняя, где вы ошиблись.

Дайте мне знать, если вам нужно что-то еще.


Оригинальный код

// This loops through each propery in data
for (var i in data.properties) {

  // EVERYTHING here is done again, each time you move onto the next property.

  // This declares the array and assigns a single value to it (the current property). 
  // It will wipe all preceding data that was previously in the array (i.e. the last property value).
  // This should be BEFORE the loop, so that you don't reset it, it will need to be created as an empty array - i.e. let dataType = [];
  // To assign the current property you need to add it to the array using dataType.push(data.properties[i].type);
  let dataType = [data.properties[i].type];

  // Prints all current contents of the array, this will print each property, but only ever the current one, and by itself
  console.log(dataType)

  // Create the autocomplete form with the current value of the array (which only holds the current value
  // This should be AFTER the loop, so that the array has been filled with all properties
  $("#searchLocation").autocomplete({
    source: dataType,
  });

}

Демо

var data = {
  "properties": [{
      "id": "prop1",
      "type": "House",
      "bedrooms": 3,
      "price": 650000,
      "tenure": "Freehold",
      "description": "Attractive three bedroom semi-detached family home situated within 0.5 miles of Petts Wood station with fast trains to London and within easy walking distance of local shops, schools, bus routes and National Trust woodland. The property comprises; two receptions, fitted 18'9 x 10'1 kitchen/breakfast room and conservatory. The property also benefits from having a utility room and cloakroom. To the first floor there are three bedrooms and a family bathroom with separate WC. Additional features include double glazing, gas central heating and a well presented interior...",
      "location": "Petts Wood Road, Petts Wood, Orpington",
      "picture": "images/prop1pic1small.jpg",
      "url": "properties/prop1.html",
      "added": {
        "month": "March",
        "day": 12,
        "year": 2018
      }
    },

    {
      "id": "prop2",
      "type": "Flat",
      "bedrooms": 2,
      "price": 299995,
      "tenure": "Freehold",
      "description": "Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat. <br>The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.<br>This apartment being only five years old, is still under a 10 year building guarantee...",
      "location": "Crofton Road Orpington BR6",
      "picture": "images/prop2pic1small.jpg",
      "url": "properties/prop2.html",
      "added": {
        "month": "September",
        "day": 14,
        "year": 2018
      }
    },
  ]
};

// Bring array outside of loop, so it doesn't reset each loop
var dataType = [];

// Cycle through each property    
for (var i in data.properties) {

  // Append autocomplete values to array  
  dataType.push(data.properties[i].type);
  dataType.push(data.properties[i].location);

}

// Add autocomplete with array as data                
$("#searchLocation").autocomplete({
  source: dataType,
});
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body>
  <form>
    <input type="text" id="searchLocation" name="searchLocation">

  </form>
</body>

</html>
0 голосов
/ 26 декабря 2018

Я думаю, вам нужно добавить следующий класс div в ваш ввод.

<div class="ui-widget">
  <input id="searchLocation"> ...
</div>
...