0

I have implemented autocomplete with jQuery AJAX. It's working fine when the screen size is half but while the screen size is full it's not working.

Another problem is that it doesn't show the result in the first input; it takes some time or when I remove the first attempt and type again in the input then autocomplete suggests result.

$(document).ready(function() {
  $("#purchase_item_search").on('keyup', function() {
    var arrayReturn = []
    $.ajax({
      url: "/products",
      dataType: 'json',
      success: function(data) {
        for (var i = 0; i < data['products'].length; i++) {
          var id = (data['products'][i].id).toString();
          arrayReturn.push({
            'data_id': id,
            'value': data['products'][i].name,
            'name': data['products'][i].name,
            'price': data['products'][i].purchase_price,
            'discount': data['products'][i].discount,
            'tax': data['products'][i].tax_id,
          })
          printProduct(arrayReturn);
        }
      }
    });

    function printProduct(arrayReturn) {
      $('#purchase_item_search').autocomplete({
        source: arrayReturn,
        select: function(event, products) {
          // Set selection
          $('#purchase_item_search').val(''); // display the selected text
          createRow(products);
          return true;
        }
      });
    }

    const tbody = document.getElementById('item_list');

    function createElement(tagName, id, className, innerHTML) {
      const element = document.createElement(tagName)
      element.id = id || ''
      element.className = className || ''
      element.innerHTML = innerHTML || ''
      return element
    }

    function createRow(products) {
      // ...
    }
  });
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="{{ asset('assets/backend/bundles/libscripts.bundle.js') }}"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
  • The issue related to screen size sounds like a CSS/media query problem. The issue with the delay sounds like standard AJAX behaviour - it's waiting for the response from your server before it can display anything in the UI. That being said, you're instantiating `autocomplete()` once for every keypress event, which is not a good idea. I'd suggest using the built-in AJAX functionality of autocomplete instead of creating your own: https://stackoverflow.com/a/21385958/519413 – Rory McCrossan Mar 28 '22 at 10:16

0 Answers0