Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image.

Below is the HTML & Java code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<div>
  <select id="color">
    <option style="display: none;">Choose Color</option>
  </select>
</div>

<div class="red box">You have selected <strong>red option</strong> so I am here
  <img src="http://i46.tinypic.com/2epim8j.jpg" />
</div>
<div class="green box">You have selected <strong>green option</strong> so I am here
  <img src="http://i49.tinypic.com/28vepvr.jpg" />
</div>
<div class="blue box">You have selected <strong>blue option</strong> so I am here
  <img src="http://i50.tinypic.com/f0ud01.jpg" />
</div>

<script>
$(document).ready(function() {
  $("select").change(function() {
    $("select option:selected").each(function() {
      if ($(this).attr("value") == "Red") {
        $(".box").hide();
        $(".red").show();
      }
      if ($(this).attr("value") == "Green") {
        $(".box").hide();
        $(".green").show();
      }
      if ($(this).attr("value") == "Blue") {
        $(".box").hide();
        $(".blue").show();
      }
    });
  }).change();
});

var select = document.getElementById("color");
var options = ["Red", "Blue", "Green"];
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
    }
</script>

CSS:

.box {
  padding: 20px;
  display: none;
  margin-top: 20px;
  border: 1px solid #000;
}
.box img {
  float: right;
  width: 150px;
  height: 100px;
}
.red {
  background: #ff0000;
}
.green {
  background: #00ff00;
}
.blue {
  background: #0000ff;
}

The functionality is working perfectly as intended.

However, I am looking to expand this functionality to around 100 fields which can be quite exhausting and inefficient to do manually (although CSS may still need manual adjustments).

My goal is to enhance the dynamic nature of my script by allowing me to add colors once in an options array, and then have the HTML and JavaScript loop through them for display actions.

Therefore, my initial question is how can I convert my HTML chunk into a loop to iterate over my options array?

Secondly, how can I streamline my code using the options array?

Thank you!

Answer №1

Check out this helpful response to kickstart your progress on the initial inquiry.

As for the second question, consider implementing a solution similar to the following:

/*  JavaScript/jQuery  */
$("select").change(function() {
    var selection = this.value;
    $('.box').hide();
    $('.'+selection).show();
});

var select = document.getElementById("color");
var options = ["red", "blue", "green"];
for(var i = 0; i < options.length; i++) {
  var opt = options[i];
  var el = document.createElement("option");
  el.textContent = opt;
  el.value = opt;
  select.appendChild(el);
}
/*  CSS Code  */
.box {
  padding: 20px;
  display: none;
  margin-top: 20px;
  border: 1px solid #000;
}
.box img {
  float: right;
  width: 150px;
  height: 100px;
}
.red {
  background: #ff0000;
}
.green {
  background: #00ff00;
}
.blue {
  background: #0000ff;
}
<!--  HTML Markup  -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

    <div>
      <select id="color">
        <option style="display: none;">Choose Color</option>
      </select>
    </div>

    <div class="red box">You have selected <strong>red option</strong> so I am here
      <img src="http://i46.tinypic.com/2epim8j.jpg" />
    </div>
    <div class="green box">You have selected <strong>green option</strong> so I am here
      <img src="http://i49.tinypic.com/28vepvr.jpg" />
    </div>
    <div class="blue box">You have selected <strong>blue option</strong> so I am here
      <img src="http://i50.tinypic.com/f0ud01.jpg" />
    </div>

Answer №2

Here is a suggestion to make the design more vibrant with dynamic colors and background boxes:

var ColorBox ={
  colors: ['Blue', 'Green'],
  init: function(){
     this.addColor();
     $('select#color').change(this.boxDisplay);
  
  },
  
  boxDisplay: function(){
    var color = $(this).val();
    $('.box').hide();
    $('.'+color).show().boxbackground(color);
  },
  
  addColor: function(){
     $.each( this.colors, function( idx, color ) {
       $('select#color').append( $('<option>',{
        value : color.toLowerCase(),
        text: color
       }))
     
     })
  }

};

$.fn.boxbackground = function( colorname ){
  elem = $(this);
  var colorcode;
  switch( colorname ){
     case 'blue' : colorcode = '#45D4FF'; break;
     case 'green' : colorcode = '#32CD32'; break;
  }
  
  elem.each( function(){
    $(this).css( 'background', colorcode );
  
  })

};
ColorBox.init();
.box {
  padding: 20px;
  display: none;
  margin-top: 20px;
  border: 1px solid #000;
}
.box img {
  float: right;
  width: 150px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select id="color">
    <option style="display: none;">Choose Color</option>
  </select>
</div>
<div class="blue box">You have selected <strong>blue option</strong> so I am here
  <img src="http://i46.tinypic.com/2epim8j.jpg" />
</div>
<div class="green box">You have selected <strong>green option</strong> so I am here
  <img src="http://i46.tinypic.com/2epim8j.jpg" />
</div>

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

retrieving data from a dropdown selection

Help! I'm stuck and need guidance. Below is the code I've been working on, attempting to set a variable using a drop-down list. Despite trying everything I can think of, I still seem to be missing something simple. Any hints or nudges in the righ ...

Performing an API request and saving the response data into a

I’m struggling to figure out how to make an API call with request in MongoDB using Mongoose. I’m new to this topic and could really use some help! Here is my test.js file, does anyone have any ideas on how to solve this issue? My goal is to save the AP ...

Make the Angular Modal scrollable except for when a specific div is being click dragged

I am working on an Ionic app that uses AngularJS. One issue I encountered is with a modal popup that can sometimes extend beyond the visible area. To address this, we applied overflow: hidden to its CSS class. However, there is a specific functionality i ...

Positioning elements in CSS relative to a specific div container

Looking for advice on how to position two images within a div using percentages relative to the parent div. Check out this fiddle for reference: http://jsfiddle.net/b9ce626s/ I experimented with setting position: absolute; on the image, but it seems to b ...

Angular array mapping techniques

My JSON Object $scope.selectedItems ={ "RECORDS": [ { "Id": 23040035705987, "arriveddate": "2015/04/24", "expirationDate": null, "replacedDate": null, "processDate": "2015/04/24" ...

Users are encountering timeout issues when attempting to connect to the Azure Postgres flexible database through the node.js server deployed on the Azure App Service

My node.js express server is deployed on Azure App Services, connecting to an Azure flexible Postgresql database. Strangely, everything works fine when running the server locally, but once it's deployed to Azure App Service, all requests time out: Th ...

Sequential asynchronous requests with a time delay

let updateData = function() { $.ajax({ . . . }) .done(function() { console.log('Update complete'); setInterval(updateData, 10000); }); } I am trying to update some data every 10 seconds. Ho ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Jade not binding correctly with Angular.ErrorMessage: Angular bindings are

Struggling with simple binding in Angular and Jade. I've tried moving JavaScript references to the end of the document based on advice from previous answers, but still no luck. Any ideas on what might be wrong? File: angular.jade extends layout blo ...

Generating a JQuery mobile page on the fly using JSON data

Currently, I am working on developing a Jquery mobile app within cordova. My goal is to dynamically construct the entire page based on Remote Restful JSON results. Since the content of this page is not fixed and will change when the JSON data on the server ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...

Node.js: Experiencing HTTP request timeout issues lasting for over a minute

Using Node.js (version 0.10.28), I encountered an issue when making an http.request to my Ruby API for a large amount of data. The request seems to time out and return a 404 error after only 1 minute. Interestingly, when using other methods like wget or jQ ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...

(JS) utilizing an external .js function by using the <script> tag

Looking to execute the function cookiefix() from main.js, which is linked at the bottom of my HTML file. echo '<body>'; if(!isset($_COOKIE['clicked'])) { if(!isset($_COOKIE['count'])) { echo '<script type="text/ ...

Prevent the cursor from exiting the div element when the tab key is pressed

Currently, I have implemented a search input box allowing users to either enter a value or select from a list of suggestions. The issue arises when the user selects an option using the tab key, as it causes the cursor to move outside the input box despite ...

Utilizing a Downloaded Font in CSS: A Step-by-Step

Just starting out here. I have a font file in .ttf format that I want to use on my blog, but I need help with obtaining its code. Am I on the right track? * { font-family: 'providence-bold'; src: url('/font/providence-bold.regular.tt ...

What methods can I implement to prevent my boxes from becoming stretched out?

How can I prevent this box from stretching too much? Here is the code snippet along with the output: CSS: .social { padding-left: 1000px; border: 5px inset black; margin: 4px; width: 100px; } HTML: <div class="social"> <p& ...

Datatables encounters issues loading 70,000 records into the system

I have a jQuery datatable that is supposed to load over 70K records. However, the datatable fails to display anything beyond 20K records. Despite trying to use the deferRender option as a workaround, it doesn't seem to be effective. $.ajax({ ur ...