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

Troubleshooting: jQuery AJAX not Invoking C# Method in ASP.NET MVC Application

I am attempting to initiate a call to the controller from the views using jQuery ajax, however, it seems like the controller is not being called. The goal is to pass the token value obtained on the registration page to the controller in order to utilize it ...

Verify that the select field has been chosen using Protractor

Currently, I am in the process of developing a test that places importance on whether a select field has already been populated. it('should automatically select a field if it hasn't been selected previously', function() { var usersField = ...

first item's grandchild selection

https://jsfiddle.net/jg69c3yf/1/ I don't have a lot of experience with CSS. My goal is to target the div with the class arrow-right, but only if it's inside the first child of a div with the class active. In this sample code, Only item 3 shoul ...

Implementing file change detection using view model in Angular

When using the input type file to open a file and trigger a function on change, you can do it like this: <input type="file" multiple="multiple" class="fileUpload" onchange="angular.element(this).scope().fileOpened(this)" /> The functi ...

Guide to customizing the appearance of a component's host element on-the-fly

For instance: https://stackblitz.com/edit/angular-mkcfsd In my project, I have an icon component called app-icon which dynamically takes a path and inserts it into an SVG viewbox. I extract the height and width of the path, then set the SVG to match those ...

Issues with Django Posts Functionality:

Currently, I am utilizing Django 1.2.3 for the development of a website. While my ajax get requests are functioning properly, the post requests only work in development mode (127.0.0.1:8000) and not when the site is deployed in production using Apache + Ng ...

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...

End the child process.execution after a specific amount of time

I have been searching for information on child process waiting time or response waiting time, but I haven't found anything useful. I'm in need of something like that, so I hope someone can assist me. When I look at the code below, I am printing ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...

When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue: const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im; re.test(control.valu ...

Using Ajax to send data to a model within another model in ASP.NET Core MVC

I'm new to this platform and I'm curious about sending model data within another model from ajax to controller. Here are my models: public class mfItems { [Key] [Display(Name = "Item ID")] public string ItemID { get; set; } ...

What could be causing express to have trouble finding the ejs file in the views directory?

Recently delved into the world of learning NodeJS and Express. // Working with express framework var express = require("express"); var app = express(); app.get("/", (req,res) => { res.render("home.ejs"); }) //Setting up port listening app.listen ...

Adjust various text lengths to fit web browser content

I am using a web browser within my Windows Form. I am populating it with text each time, with almost the same text size in each loop. The size of my web browser is fixed, and I want to automatically adjust the text content to fit the browser. For example, ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Creating HTML content in a new window with Vue.js - a step by step guide

Recently, I encountered a problem with jsPDF regarding Unicode support in table generation. To work around this issue, I decided to utilize the browser's print feature instead. I achieved this by creating a new HTML document with the table and display ...

I am experiencing an issue where I cannot select a row in datatables to transfer the data to a text field in Laravel 5

I am currently working on a web application using Laravel 5.4. There are certain modules where I have a main form that triggers datatables to appear in a modal dialog window (for example: when I click on a search button, the modal window displays datatable ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

Issues with Pageinit and Ready Event Timings

Check out this fiddle where I am experiencing an issue related to pageinit and ready events In the fiddle, everything functions properly using onLoad and onDOMready. This includes: The subject listings are loaded correctly with a popup displaying module ...

Navigation buttons that move the user either up or down the page

I am a beginner in programming and I wanted to create two buttons for my webpage. One button should appear when the page is scrolled more than 300px and take the user to the top, while the other button should be displayed immediately and scroll the user to ...