Search code examples
javascriptdatalist

Load JSON file to datalist input


I want to load to datalist from a JSON file. My JSON file has 2 attributes and looks like:

[ {
    "product":"1235",
    "description":"description 1"
  },
  {
    "product":"1325",
    "description":"description 2"
  }, 
  ...
]

And the JavaScript code

var dataList = document.getElementById('json-datalist');
var input = document.getElementById('ajax');
var request = new XMLHttpRequest();

request.onreadystatechange = function(response) {
  if (request.readyState === 4) {
    if (request.status === 200) {
      // Parse the JSON
      var jsonOptions = JSON.parse(request.responseText);

      // Loop over the JSON array.
      jsonOptions.forEach(function(item) {
        // Create a new <option> element.
        var option = document.createElement('option');
        // Set the value using the item in the JSON array.
        option.value = item;
        // Add the <option> element to the <datalist>.
        dataList.appendChild(option);
      });

      // Update the placeholder text.
      input.placeholder = "e.g. datalist";
    } else {
      // An error occured :(
      input.placeholder = "Couldn't load datalist options :(";
    }
  }
};

// Update the placeholder text.
input.placeholder = "Loading options...";

// Set up and make the request.
request.open('GET', 'myfile.json', true);
request.send();

The state is at "Loading options" and doesn't change. If I alter the JSON, like

[ 
   "product",
   "description"
]

Then it works and "product", and "description" are shown as possible choices.. What I have to edit in the JavaScript in order to show only the element product?


Solution

  • You're trying to set the option value to an object:

    option.value = item;
    

    To use just the product member, do so explicitly:

    option.value = item.product;
    

    You could also include the description as the visible option text:

    option.text = item.description;
    

    var dataList = document.getElementById('json-datalist');
    
    var jsonOptions = [{
      "product": "1235",
      "description": "description 1"
    }, {
      "product": "1325",
      "description": "description 2"
    }];
    
    // Loop over the JSON array.
    jsonOptions.forEach(function(item) {
      var option = document.createElement('option');
      
      option.value = item.product;
      option.text = item.description;
    
      dataList.appendChild(option);
    });
    <select name="" id="json-datalist">
    </select>