Search code examples
jquery-uibootstrap-modal

Autocomplete in a modal is not listed/populated


I am creating an 'assign button' which calls a modal. In this modal will search a username queried from a database table. This autocomplete should be listed in the modal box, in fact it is not. I am using Jquery UI for this.

Modal

The "No search result" text is behind the modal, as well the assignee is listed behind the modal.

I am detailing my code in this jsfiddle

This is my original code:

$("#user_name").autocomplete({
  source: function(request, response) {
    $.ajax({
      url: "https://dummyjson.com/products",
      // url: "<?= site_url('Inventory/readuser'); ?>",
      method: "get",
      dataType: "json",
      data: {
        term: request.term
      },
      success: function(data) {
        console.log("response --> ", data);
        response(data); //callback fn                    
      }
    }) //ajax
    console.log("ok");
  }, //source
  select: function(event, ui) {
    $('[name="username"]').val(ui.item.username);
    $('[name="role"]').val(ui.item.role);
    $('[name="location"]').val(ui.item.location);
  }
}); //#user_name
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js" integrity="sha512-57oZ/vW8ANMjR/KQ6Be9v/+/h6bq9/l3f0Oc7vn6qMqyhvPd1cvKBRWWpzu0QoneImqr2SkmO4MSqU+RpHom3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

  <a href="#updateUser" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm mb-3 small" data-bs-toggle="modal" data-bs-target="#updateUser"><i class="bx bxs-filter-alt text-white-50"></i>Assign</a>
</div>


<div class="modal fade" id="updateUser" tabindex="-1" aria-labelledby="updateUser" aria-hidden="true">
  <div class="modal-dialog modal-dialog-sm modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Assign user ...</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <fieldset class="border rounded-3 p-2">
          <legend class="float-none w-auto px-2 small">type a user name</legend>
          <div class="frmSearch">
            <input type="text" class="form-control form-control-sm" id="user_name" name="user_name" size="20" maxlength="3">

            <div id="suggesstion-box"></div>
          </div>
        </fieldset>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-save-filter" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary btn-save-filter" data-bs-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>

but in fiddle I am using dummy json from https://dummyjson.com/docs/products

Please advise how to put the listed value into the green box in the modal.


Solution

  • Please review the following:

    https://jsfiddle.net/Twisty/orv2j67n/1/

    JavaScript

    $("#user_name").autocomplete({
      appendTo: "#suggestion-box",
      source: function(request, response) {
        $.ajax({
          url: "https://dummyjson.com/products",
          method: "get",
          dataType: "json",
          data: {
            term: request.term
          },
          success: function(data) {
            var results = $.map(data.products, function(v, i) {
              v = $.extend(v, {
                label: v.brand,
                value: v.brand
              });
              return v;
            });
            console.log(results);
            response(results);
          }
        });
        console.log("ok");
      },
      select: function(event, ui) {
        $('[name="label"]').val(ui.item.title);
      }
    });
    

    Two changes to be aware of:

    appendTo: "#suggestion-box",
    

    Which element the menu should be appended to. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.

    I also added a $.map() in the Success. This ensure that the proper elements exist when passing the data back to response().

    var results = $.map(data.products, function(v, i) {
      v = $.extend(v, {
        label: v.brand,
        value: v.brand
      });
      return v;
    });
    console.log(results);
    response(results);
    

    This is discussed here: https://api.jqueryui.com/autocomplete/#option-source

    An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]