AnswerBun.com

Autocomplete form field with JQuery from external JSON not working

Stack Overflow Asked by Solar on October 7, 2020

The first step of my complex form is to autocomplete a field with some external data located in a json. I tried and followed multiple examples and documentation but I am unable to make it work…

For this external json:

[
  {
    "Nombre": "Adoración Pérez",
    "DNI": "23123",
    "Telefono": ""
  },
  {
    "Nombre": "Adriana Suárez",
    "DNI": "345345435",
    "Telefono": ""
  },
  {
    "Nombre": "Agueda Delmiro",
    "DNI": "6u56u6tJ",
    "Telefono": 12312434
  },
  {
    "Nombre": "Aida Aguilera",
    "DNI": "46456456A",
    "Telefono": 13123213
  },
  {
    "Nombre": "Aladino Valdés",
    "DNI": "67867845eG",
    "Telefono": ""
  },
  {
    "Nombre": "Alberto Martinez",
    "DNI": "235436456",
    "Telefono": ""
  }
]

This is my full JS:

$(function() {

    var entries = []

    $.getJSON('pacientes.json', function(json) {
        for (var key in json) {
            if (json.hasOwnProperty(key)) {
                var item = json[key];
                entries.push(item);
            }
        }

        console.log(entries)

        $("#species").autocomplete({
            minLength: 0,
            source: entries,
            focus: function(event, ui) {
                $("#species").val(ui.item.Nombre);
                return false;
            },
            select: function(event, ui) {
                $("#species").val(ui.item.Nombre);
                $( "#identifiant" ).val( ui.item.DNI );

                return false;
            }
        })
    });


});

This is my full HTML:

<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

<form action="/action_page.php">
  <label for="species">Species: </label>
  <input id="species">
  <label for="identifiant">Identifiant: </label>
  <input id="identifiant" style="width: 6em;">
</form> 

<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>

<script src="js/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/parse_data.js"></script>


</body>
</html>

I tried several different options but cannot autocomplete data. Thank you very much!

One Answer

Consider the following example.

$(function() {
  // Load entries once
  var entries = [];
  $.getJSON('pacientes.json', function(json) {
    $.each(function(key, val) {
      if (json.hasOwnProperty(key)) {
        entries.push(json);
      }
    });

    // Initialize Autocomplete
    $("#species").autocomplete({
      minLength: 0,
      source: function(req, resp) {
        var myData = [];
        $.each(entries, function(key, val) {
          if (val.Nombre.indexOf(req.term) == 0) {
            myData.push({
              label: val.Nombre,
              value: val.DNI,
              Nombre: val.Nombre,
              DNI: val.DNI,
              Telefono: val.Telefono
            });
          }
          console.log(myData);
          resp(myData);
        });
      },
      focus: function(event, ui) {
        $("#species").val(ui.item.Nombre);
        return false;
      },
      select: function(event, ui) {
        $("#species").val(ui.item.Nombre);
        $("#identifiant").val(ui.item.DNI);
        return false;
      }
    });
  });
});
<h2>HTML Forms</h2>

<form action="/action_page.php">
  <label for="species">Species: </label>
  <input id="species" type="text" />
  <label for="identifiant">Identifiant: </label>
  <input id="identifiant" type="text" style="width: 6em;" />
</form>

<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>

<script src="js/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/parse_data.js"></script>

This will allow you to configure custom data and still format the Array as needed.

Reference: https://api.jqueryui.com/autocomplete/#option-source

You can also make use of $.ui.autocomplete.filter().

var myData = [];
$.each(entries, function(key, val) {
  myData.push({
    label: val.Nombre,
    value: val.DNI,
    Nombre: val.Nombre,
    DNI: val.DNI,
    Telefono: val.Telefono
  });
  console.log(myData);
  resp($.ui.autocomplete.filter(myData, req.term));
});

Answered by Twisty on October 7, 2020

Add your own answers!

Related Questions

Find the best matching combination of numbers

0  Asked on December 18, 2020 by stkvtflw

     

toUpperCaseFunction does not work with await keyword

2  Asked on December 18, 2020 by goxarad784

   

How to split given linked list

1  Asked on December 18, 2020 by evgeni-nabokov

   

delete bigquery table from spark by using scala

1  Asked on December 17, 2020 by counter10000

     

Python : find_all() return an empty list

2  Asked on December 17, 2020 by bastien

     

expected false to deeply equal true on postman

2  Asked on December 17, 2020 by cristian-hernandez

   

Split the data in the specific column in the DataFrame

2  Asked on December 17, 2020 by jaehyeon-robert-han

   

preventDefault not working when form submit react js

2  Asked on December 17, 2020 by gihankumara

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP