How to use JavaScript Dropdown with JSON Data | CodeLSC

 


If you're building a web application that requires a dropdown menu that's populated with data from a JSON file, JavaScript can help make it happen. In this tutorial, we'll show you how to use JavaScript to create a dropdown menu that's populated with JSON data.

 

Demo:


Step 1: Create the HTML

To start, we'll create an HTML file with the necessary elements for our dropdown menu. Here's the code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>JSON Data with Dropdowns</title>
    <link rel="stylesheet" href="style.css" />
    <link
      href="https://fonts.googleapis.com/css?family=Hug+Me+Tight&display=swap"
      rel="stylesheet"
    />
  </head>
  <body>
    <!-- Container for the dropdown menu and result display -->
    <div class="container">
      <h1>Select a Fruit:</h1>
      <!-- Dropdown menu for selecting fruits -->
      <select id="fruit">
        <option value="">--Select--</option>
      </select>
      <!-- Paragraph tag for displaying the selected fruit -->
      <p id="result"></p>
    </div>
    <!-- Script tag for loading the JavaScript code -->
    <script src="script.js"></script>
  </body>
</html>

In this code, we have a div with a class of "container" that will hold all of our elements. Inside the container, we have an h1 tag with the title "Select a Fruit:", a select element with an id of "fruit", and a p tag with an id of "result". The select element has one option element with a value of "", which will be replaced with our JSON data.

 

Step 2: Create the JSON file

Next, we'll create a JSON file with the data that we want to use for our dropdown menu. Here's an example of what the file might look like:

[
  {
    "name": "Apple",
    "color": "Red"
  },
  {
    "name": "Banana",
    "color": "Yellow"
  },
  {
    "name": "Orange",
    "color": "Orange"
  },
  {
    "name": "Grape",
    "color": "Purple"
  }
]

In this code, we have an array of four objects. Each object represents a fruit and has two properties: name and color.

 

Step 3: Create the JavaScript

Now we'll create a JavaScript file that will fetch the JSON data and populate the dropdown menu. Here's the code:

<!-- JavaScript code for populating the dropdown menu and displaying the selected fruit -->
<script>
  // Array of fruits with their names and values
  const fruits = [
    { name: 'Apple'value: 'apple' },
    { name: 'Banana'value: 'banana' },
    { name: 'Orange'value: 'orange' },
    { name: 'Pineapple'value: 'pineapple' },
    { name: 'Strawberry'value: 'strawberry' },
  ];
 
  // Get the dropdown element
  const dropdown = document.getElementById('fruit');
 
  // Function for populating the dropdown menu with fruits
  function populateDropdown() {
    for (let i = 0i < fruits.lengthi++) {
      let option = document.createElement('option');
      option.value = fruits[i].value;
      option.text = fruits[i].name;
      dropdown.appendChild(option);
    }
  }
 
  // Call the function to populate the dropdown menu
  populateDropdown();
 
  // Get the result paragraph element
  const result = document.getElementById('result');
 
  // Add an event listener to the dropdown menu to display the selected fruit
  dropdown.addEventListener('change'function () {
    result.innerHTML = 'You selected ' + this.value;
  });
</script>

In this code, We loop through the fruits array and create an option element for each fruit with the name as the value and text.

 

Finally, we add an event listener to the select element that updates the content of the result paragraph tag with the selected fruit.

 

Step 4: Style the Page

To make the page look more professional, we'll add some CSS. Here's the code:

.container {
  displayflex;
  flex-directioncolumn;
  align-itemscenter;
  justify-contentcenter;
  height100vh;
  background-imageurl("https://wallpaperaccess.com/full/3899650.jpg");
  background-repeatno-repeat;
  background-sizecover;
  font-family'Hug Me Tight'cursive;
}

#fruit {
  padding10px;
  font-size16px;
  bordernone;
  background-color#f2f2f2;
  border-radius5px;
  box-shadow0 2px 2px rgba(0000.1);
  appearancenone;
  -webkit-appearancenone;
  -moz-appearancenone;
}

#fruit:focus {
  outlinenone;
  box-shadow0 0 3px #2196F3;
}

#result {
  margin-top20px;
  font-size20px;
  font-weightbold;
  text-aligncenter;
}

 

In this code, we're setting the font family to Hug Me Tight, making the page center aligned, and adding some styles to the container, h1, select, and p elements.

 

Conclusion

With just a few lines of code, we've created a dropdown menu that's populated with data from a JSON file using JavaScript. By styling the page with CSS, we can make it look more professional and presentable.


Follow us on social media for more coding tips and updates:

YouTubehttps://www.youtube.com/@codelsc

InstagramInstagram@codelsc_0122




#JavaScript #JSON #DropdownMenu #HTML #CSS #WebDevelopment #Programming #FrontEndDevelopment

Comments