🚀 Check whether your JSON dataset is valid or not and then proceed.
Bind SELECT Element with JSON Array using JavaScript
I’ll first create a JSON array inside a JavaScript function and add few data to it. Next, I’ll iterate (loop) through each value in the array and bind the values to the SELECT element.
<html> <head> <title>Bind SELECT Dropdown with JSON using JavaScript</title> </head> <body> <p> <input type="button" onclick="populateSelect()" value="Click to Populate SELECT with JSON" /> </p> <!--The SELECT element.--> <select id="sel" onchange="show(this)"> <option value="">-- Select --</option> </select> <p id="msg"></p> </body> <script> function populateSelect() { // THE JSON ARRAY. let birds = [ {"ID": "001", "Bird_Name": "Eurasian Collared-Dove"}, {"ID": "002", "Bird_Name": "Bald Eagle"}, {"ID": "003", "Bird_Name": "Cooper's Hawk"}, ]; let ele = document.getElementById('sel'); for (let i = 0; i < birds.length; i++) { // POPULATE SELECT ELEMENT WITH JSON. ele.innerHTML = ele.innerHTML + '<option value="' + birds[i]['ID'] + '">' + birds[i]['Bird_Name'] + '</option>'; } } function show(ele) { // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT. let msg = document.getElementById('msg'); msg.innerHTML = 'Selected Bird: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' + 'ID: <b>' + ele.value + '</b>'; } </script> </html>
See how I got the selected text of the SELECT element in the above example.
ele.options[ele.selectedIndex].text
Fetch (or extract) Data from an external JSON File and Bind Data to <select> dropdown list
🚀 Do you know you can check weather a JSON is Valid or not with the click of a button? Check this out.
The markup for this example remains the same as above.
<body> <select id="sel" onchange="show(this)"> <option value="">-- Select --</option> </select> <p id="msg"></p> </body> <script> window.onload = populateSelect(); function populateSelect() { // CREATE AN XMLHttpRequest OBJECT, WITH GET METHOD. var xhr = new XMLHttpRequest(), method = 'GET', overrideMimeType = 'application/json', url = '../../library/sample.json'; // ADD THE URL OF THE FILE. xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // PARSE JSON DATA. let birds = JSON.parse(xhr.responseText); let ele = document.getElementById('sel'); for (let i = 0; i < birds.length; i++) { // BIND DATA TO <select> ELEMENT. ele.innerHTML = ele.innerHTML + '<option value="' + birds[i].ID + '">' + birds[i].Name + '</option>'; } } }; xhr.open(method, url, true); xhr.send(); } function show(ele) { // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT. var msg = document.getElementById('msg'); msg.innerHTML = 'Selected Bird: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' + 'ID: <b>' + ele.value + '</b>'; } </script>
In the above example, I am using XMLHttpRequest() objects to connect with a JSON file.
XMLHttpRequest, provides the necessary methods and properties to interact with server objects, asynchronously. It is used extensively with Ajax applications.
By the way, there's another simple method in JavaScript that you can use to fetch data from external files. See this article. This method uses async and await. Its a must see article.
Note: Some old Internet Explorer versions do not support XMLHttpRequest objects.
👉 Do you know you can create a Cascading SELECT dropdown list using JSON data? See this post.
Next, I am using the property onreadystatechange to execute a callback function. Since, its an asynchronous process, callback function is executed only when the file is fully loaded.
xhr.onreadystatechange = function () {
…
}
With this condition, if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200), I am checking if the request is successful. Check the two properties in your browser console.
console.log(xhr.readyState); console.log(xhr.status);
After we have checking the state of the request, we’ll parse or extract data from JSON file using XMLHttpRequest’s responseText property.
var birds = JSON.parse(xhr.responseText);
The binding of JSON data to the <select> element is similar to the process I have explained the first example above.