What is the best way to implement a dropdown menu with JavaScript or jQuery?

I'm looking to create a dynamic dropdown list using Javascript or JQuery that mirrors the functionality of selecting countries, states, and cities. Can someone provide guidance on the best code to achieve this? Below is a snippet of my existing code:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
...
</script>
</body>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

<script type="text/javascript">
    $('#btn01').click(function () {       
        $("#my_image").attr("src", "empty.png");
    });
    $('#btn02').click(function () {       
        $("#my_image").attr("src","Sequence01_1.gif");
    });
    $('#btn03').click(function () {       
        $("#my_image").attr("src", "BLASTFURNACE.png");
    });
</script>
</html>

Answer №1

$(document).ready(function () {
  const exampleArray = [
    {id: 1, name: "example"},    {id: 1, name: "example"},
    {id: 1, name: "example"},
    {id: 1, name: "example"},
    {id: 1, name: "example"},
    {id: 1, name: "example"},
  ]
  
  if(exampleArray) {
   $("#stateLint").css({ display: "block" });
   exampleArray.map(ex => {
    $("#countryName").append( $(`<option>`, {
                value: ex.id,
                text: ex.name,
              }))
  })
   }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "stateLint" style="display: none">
  <select id="countryName"></select>
</div>;

You have the ability to achieve this in a similar manner

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A dynamic JavaScript object that functions similarly to a multidimensional associative array in PHP

How can you efficiently update or add properties to an object in JavaScript? Unlike PHP's associative array, achieving this dynamically in JavaScript can be a bit tricky. For example: $test = []; foreach ($data as $key => $value) { ... $te ...

The dropdown feature functions properly on Chrome but seems to be malfunctioning on

Dropdown list inside the HTML header table My query was addressed in the link above, however, the solution only seemed to work on Chrome and not Firefox. I specifically want the dropdown arrow header to be displayed next to the table header instead of bel ...

Ways to reposition JavaScript output within a webpage

I am new to HTML, CSS, and JavaScript and I have a question regarding how they work together. I can use JavaScript to display objects on the page, but I'm unsure how to move them around like other elements. Is CSS the solution for this? Any advice w ...

Utilizing const as the iteration variable in a for loop

I've grasped the concept of using var and let in a for loop in typescript/javascript, but can someone shed light on how and why a const variable as a loop variable behaves? for (const i = 0; i < 5; i++) { setTimeout(function() { console.log( ...

If the <option> is chosen, execute the query one more time

On my form, I have a Category dropdown menu that is dynamically populated by a PHP script querying names from a MySQL table. Adjacent to the Category dropdown, there is also a Subcategory dropdown menu populated using another PHP script and querying a dif ...

Is it possible to design this without JavaScript, using only CSS3 and HTML5?

Is it possible to achieve this design using only CSS3 and HTML5, without the use of JavaScript? Header (includes an image) : Height: flexible (depends on the width of the image) Position: fixed Content (contains text) : Height: flexible (height of l ...

What is the basic structure of a JSON-like object?

How can data be effectively stored in a JSON-like structure? I have noticed two different approaches to storing data within a json object, each with its own method for accessing the data (illustrated using examples in Python): Approach 1: obj1 = [ {" ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Solving the issue of "_c is not defined" error in Vue functional component

I've been experimenting with creating functional components in Vue using the render method. Here's an example of how I attempted to do this: import Vue from "vue" const { render, staticRenderFns } = Vue.compile(`<div>Hello World</div&g ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

HTML/CSS - Enhances user experience by zooming in on select tag when tapped on mobile devices

I am experiencing an issue with a select menu on mobile devices. Whenever I tap on the menu, it seems to zoom in slightly. Is there a particular -webkit property causing this behavior? How can I prevent the screen from zooming when I tap on the select me ...

Passing a JSON file name as an argument to a command line in Node.js

When I run app.js using the command node app.js, it will execute const inputData = require('./input.json'); Now, my question is - can I pass the file name as an argument to const inputData = require('./file.json'); directly from the co ...

Button styles that have been verified will not be shown in Firefox

Hello, first time poster here! Client specifications for CSS: button { border: 1px solid #B8B7B8; border-radius: 8px; height: 4em; margin: 25px 2px 25px 0; text-align: center; text-decoration: none; width: 4em; } button:active, button:che ...

Comparison of efficiency in declaring JSON data using JSON.parse versus an object literal

In a recent video from the 2019 Chrome Dev Summit titled "Boosting App Speed with JSON.parse", it was revealed that utilizing JSON.parse with a string literal instead of an object literal can result in a significant enhancement in speed. The official Googl ...

unable to retrieve data from MongoDB using db.find

I am currently working with a script that I run through the mongo shell. The first query for posts works perfectly and I am able to receive the data object without any issues. Even when I print the date after running it through the convertDate function, ...

Using three.js to input text instead of particles within a particle cloud

I have a unique three.js codepen project where square particles drift through the space. However, I am now looking to enhance it by incorporating text (perhaps using geometry?) instead of the square particles, creating a word/tag cloud effect. Is this eve ...

Unexpected issue on AngularJS application

Encountering issues with incorporating a controller into my page - each time I add it to a DOM element, an error is thrown. Here's the structure of my HTML page: <html data-ng-app="sportsStore"> <head> <title>Sports Sto ...

Struggling to successfully toggle the visibility of items

I am currently facing an issue with displaying different sets of data based on button clicks. The first block of information is showing correctly upon page load, but when I try to display other blocks by clicking on the corresponding buttons, the info cont ...