With an external file, I mean a .json file, stored locally or in a remote server.
👉 Now if you want you can also convert JSON data dynamically to an HTML table using Plain old JavaScript
The JSON
Open a NotePad and save the file with a name sample.json. Add below data to the file and save it.
[ { "ID": "001", "Name": "Eurasian Collared-Dove" }, { "ID": "002", "Name": "Bald Eagle" }, { "ID": "003", "Name": "Cooper's Hawk" }, { "ID": "004", "Name": "Bell's Sparrow" }, { "ID": "005", "Name": "Mourning Dove" } ]
The Code
I am using jQuery .getJSON() method to extract data from the JSON file. After extracting the data, I’ll iterate or loop through each requested JSON data and insert it into the SELECT element using jQuery append() method.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head> <body> <p> <input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" /> </p> <select id="sel"> <option value="">-- Select --</option> </select> <p id="msg"></p> </body> <script> $(document).ready(function () { $('#bt').click(function () { var url = "https://www.encodedna.com/library/sample.json"; $.getJSON(url, function (data) { $.each(data, function (index, value) { // APPEND OR INSERT DATA TO SELECT ELEMENT. $('#sel').append('<option value="' + value.ID + '">' + value.Name + '</option>'); }); }); }); // SHOW SELECTED VALUE. $('#sel').change(function () { $('#msg').text('Selected Item: ' + this.options[this.selectedIndex].text); }); }); </script> </html>