Modify the Div background color by accessing the HEX value saved in a JSON file

(I made a change to my code and removed the br tag from info2)

Currently, I have successfully implemented a feature using jQuery that reads color names and hex values from a JSON file, populates them in a drop-down select menu (which is working fine). Now, I am looking to enhance this functionality where I want the background color of a div next to the drop-down to dynamically change based on the color selected by the user. How can I achieve this?

Here's a snippet of my page:

<script language="javascript" type="text/javascript">
    
        var JSON_Response;
    
        $(document).ready(function () {
    
            $.getJSON('Colors.json', function (data) {
                JSON_Response = data;  
    
                var mySelect = document.getElementById("selColor");
    
                for (i = 0; i < JSON_Response.Colors.length; i++) {
                    var myOption = document.createElement("option");
                    myOption.text = JSON_Response.Colors[i].colorName;
                    myOption.value = i;
                    try {
    
                        mySelect.add(myOption, mySelect.options[null]);
                    }
                    catch (e) {
                        mySelect.add(myOption, null);
                    }
                } 
    
            }); 
    
            $("#selColor").change(function () {
                var myIndex = $("#selColor").val();
                $("#showColor").attr("src", JSON_Response.Colors[myIndex].hex);
    
                var info = JSON_Response.Colors[myIndex].colorName + "<br />";
                info += JSON_Response.Colors[myIndex].hex+ "<br />";
                var info2 = JSON_Response.Colors[myIndex].hex;
                $("#divDisplay").html(info).css({'background-color' : '#' + info2});
    
    
            }); 
        });     
    
        </script>
    

Answer №1

Avoid adding <br /> to the end of the info2 variable, as it should only store a hexadecimal color code.

var info2 = JSON_Response.Colors[myIndex].hex;

Answer №2

Essentially, you've got it. The mistake lies in the background-color value that you're assigning to the div.

$("#divDisplay").html(info).css({'background-color' : '#' + info2});

The correct version should be:

$("#divDisplay").html(info).css({'background-color' : '#' + JSON_Response.Colors[myIndex].hex});

Here is a basic working fiddle example

<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
    <button>Click me</button><br/>
    <div id="myDiv" style="height:400px;width:400px;">
    </div>

    <script>
    var hexChars = "ABCDEF0123456789";

    function getColor() {
        var colorStr = "";

        for(var idx=0; idx < 6; idx++ ) {
                colorStr += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
        }

        return colorStr;
    }

    $('document').ready(function() {
        $('button').click(function() {
            var rand = getColor();

            $('#myDiv').html('#' + rand).css({ 'background-color' : '#' + rand });
        });
    });
    </script>
</body>
</html>

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

jQuery load fails to fill select dropdown

Upon page load, my code executes a call to mysql to populate a select element with data. This process works smoothly on the initial load or when the page is refreshed. However, I am encountering an issue when attempting to update or repopulate the select e ...

What sets apart the HTML tags for embed, object, and video elements?

Can you explain the technical distinctions among these three tags and provide reasons why one might be chosen over another? Additionally, why did the embed tag lose popularity in HTML 4 and get replaced by object, only to see a resurgence in HTML 5 while ...

Show data from an API in an HTML table

I encountered an issue with an API, and despite trying console.log(response.[""0""].body) to view the response in the console, it does not seem to be working. My goal is to extract all the data from the API and display it in a table. Below is my code: ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

Using AJAX to Post Data with Relative Path in ASP.NET MVC 5

I have been developing an MVC 5 web application that utilizes AJAX Posts to invoke Controller Actions. For example, I have a controller named "Account" with an action called "Create". In my Account/Index view, which is rendered by accessing an Account/Ind ...

The text entered in the textbox vanishes after I press the submit button

When a user selects a value in a textbox and clicks the submit button, the selected value disappears. <div class="panel-body" ng-repeat="patient in $ctrl.patient | filter:$ctrl.mrd"> <form> <div class="form-group"> ...

Unexpected outcomes from executing the Bash and echo commands

My bash script is giving unexpected results when I run an echo command. Here's the code snippet causing the issue: echo "{ "outputs": { "result": "[{\"directory\":\"mydir\&quo ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

Navigational Menu in PHP

My goal is to have one link that retrieves data from a table with a specific value and another identical link that pulls data from the same table but with a different value. However, both dropdowns are displaying in the link. <div class="col-sm-9"> ...

Utilizing SwiftyJSON for converting JSON strings to Swift objects

What is the best approach to map a JSON string to a Swift object? struct User { var name: String var age: Int } Is there a simple method for converting a User object to a JSON string and vice versa, for mapping a JSON string to a User object? ...

What is the best way to utilize the GET Method with a hashtag incorporated into the URL?

For instance: www.sample.com#?id=10 Currently, I am not able to retrieve any value from $_GET['id']. Despite my attempt to eliminate the hashtag from the URL using JavaScript, no change occurs: $(document).ready(function(){ $(window.location ...

Encountering a parse error when making an AJAX call using structural functions

I'm in the process of developing an API and here is my PHP function. function retrieve_schools($cn){ $schools_query = "SELECT * FROM schools"; $school_result = mysqli_query($cn, $schools_query); $response_array['form_data'][&apo ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

Include the timestamp of the present moment and update the JSON data structure using Python

After successfully scraping news portal data and storing it in a DataFrame, I exported the data to both csv and json formats. The export to csv went smoothly, and there were technically no issues when exporting it to json as well. Below is the sample resul ...

Iterating over numerous data points within a JSON file and leveraging a single value for each instance in Gatling

Here is an interesting coding scenario I encountered: > .exec(http("get print package") > .get("url.json") > .headers(headers_0) > .check(jsonPath("$..shapes[?(@.state=='UNUSED'&& @.assetId==null ...

Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

Utilizing Material UI's TextField components for validating React forms

I've spent the past hour researching this topic and unfortunately, there isn't much information available on the internet. My goal is to validate input fields to ensure that all fields are filled out; otherwise, an error will be displayed. The le ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...