Apply the jQuery class to each JSON result to style it with CSS

I'm currently working on enhancing the filter options in my online store by incorporating color coding. I have successfully saved the color codes and now retrieve them through json. My goal is to add these color codes to the parent class above the input element. While I have managed to modify the class name as needed for other functionalities, I am now facing the challenge of arranging the color codes in the proper order when returned by json.

Here is an overview of my progress:

    function onDataReceived(data) {
        for (var i = 0; i < data.colorInfo.length; i++) {
            console.log(data.colorInfo[i].colorCode);
        }

        $('input[id^="filter_"]').each(function(){
            $(this).parent().attr('class','addedClass');
            $(this).parent().parent().attr('class','addedClass');
        });
    }

    $(document).ready(function () {

            var url = 'myjsonlink.json';
            $.get(url, onDataReceived);

    });

The line containing console.log(data.colorInfo[i].colorCode); displays the 3 necessary color codes like #fff, etc. Is there a way to insert each of these results above the 3 inputs I possess?

What I aim to accomplish is:

<div style="background-color: data.colorInfo[i].colorCode"> <input> </div>

Just like that!

Answer №1

function displayFilteredColors(data) {
    //for (var i = 0; i < data.colorInfo.length; i++) {
    //    console.log(data.colorInfo[i].colorCode);
    //}
    var totalColors = data.colorInfo.length;

    $('input[id^="filter_"]').each(function(index){
        $(this).parent().addClass('newClass');//attr('class','addedClass');
        $(this).parent().parent().addClass('newClass')
               .css('background-color',"'" + data.colorInfo[index % totalColors].colorCode + "'");
//.attr('class','addedClass');
    });
}

Answer №2

One way I would approach this is by extracting the string containing class names from the DOM element:

var classString = $(this).parent().attr('class','addedClass');

Next, I would split the string and iterate through it:

var newClasses = []; //initialize the new classes array
var classes = classString.split(/ /);
for(var a=0; a<classes.length; a++){
    var colorObj = data.colorInfo[a]; //retrieve the relevant color object
    if(colorObj){
        newClasses.push(classes[a] + '-' + colorObj.colorCode); //
    }
}

Finally, I would update the old classes with the newly generated ones:

$(this).parent().attr('class', newClasses.join(' '));

This method may work for your situation. It's always good to test it before implementation ;)

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

Updating elements in a table view using Titanium

Hey there! I'm currently working on an Android application using Titanium. I've encountered a problem with changing images upon click using the code below. The issue is that the image only changes once, upon the first click. Subsequent clicks do ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...

Utilize the child array to retrieve the total number in the table

Dealing with JSON data, my task is to count the number of strings within a specific child element and then group them by part of the string to create a table. While this may seem like a confusing and daunting challenge, it's what we need to accomplish ...

The power of ReactJS and the mysterious nature of 'this'

The code below is currently functioning: fetchPost (id) { var mainObject = {}, toReturn = [], promises = []; var that = this; for(var i=id; i<10; i++) { promises.push(axios.get(`api/posts/${i}`)); } axios.all(promises).then(function(resul ...

validate that the input contains only numbers within the range of 5 to 60

I need to validate inputted numbers within the range of 5-60. <div class="col-md-3"> <input type="text" name="gd_time" id="gd_time" placeholder="Enter a number between 5 and 60 " class="form-control"> </div> The script I have attemp ...

What is the reason for having two elements positioned just 50 pixels apart, with the top element having a margin-bottom of 50px and the bottom element having a margin-top of 50px

I have encountered a strange issue while trying to ensure that two elements remain consistently 100 pixels apart in my code. Despite having no errors, the margin-bottom on the P tag is set to 50 pixels and the margin-top on a DIV below it is also set to 50 ...

Utilizing uppercase formatting on lowercase categories

I have always believed that HTML/CSS classes are case sensitive, but I am finding the opposite to be true in my current experience. https://i.sstatic.net/HIxSb.png Is there a way to make it case sensitive? ...

What sets Legacy JavaScript apart from its modern counterpart, JavaScript?

Exploring the distinctions in coding practices between JavaScript and jQuery, I came across an interesting concept known as Legacy JavaScript that I was previously unaware of. You can read more about it at this link: Selecting Elements in Different Ways: ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Issue with NodeJS: Unable to locate module 'io' (socket.io in combination with express version 4.15.3)

I am a beginner in NodeJS and I am attempting to create a simple chat application using the express and socket.io modules. However, when I try to run the application, I encounter an error on the page where I am utilizing the socket feature. The console dis ...

Is there a way to retrieve multiple results by utilizing fetch and randomuser.me?

I am currently working with the randomuser.me API and have set up the fetch request correctly. My goal is to retrieve 5 users separated by commas instead of just one. As mentioned in randomuser.me's documentation, I simply need to append the fetch UR ...

"Patience is key when it comes to waiting for components to render

Short Overview of the Issue I'm currently exploring methods to access an onRendered lifecycle hook. Finding on the Topic A similar query was posted here: Vue $nextTick in mounted() hook doesn't work as expected The explanation provided suggests ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. https://i.sstatic.net/cYwwW.jpg See the code snippet below ...

Determining if a JavaScript variable points to another variable

Is there a way to identify if a variable is simply a reference to another object, and if so, determine the original variable name? For example, when trying to json encode an object that contains a property referencing back to the original object, it can l ...

How can I bind an event for changing innerHTML in Angular 2?

Is there a way to implement something similar to this: <div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div> Currently, I have a variable content that is updated by a service fetching a string from my express server. The content ...

Tips for employing duplicated HTML on a webpage

I have developed a main menu for my website using html and css. It seems cumbersome to manually copy and paste this menu into every single file or page on the website whenever I make edits. Is there a way for this main menu to automatically appear on every ...

Should npm run start be used instead of npm start in Create React App?

The starting point for our application in Create React App is npm start. However, when we want to build the app, we use npm run build instead of npm run start. It may be confusing why npm start works this way. Is it a default npm script command? ...

Is there a way to input two different values into my search bar?

I've been attempting to enhance my searchbar by adding the value of "organization.name" to filter the list along with "organization.topic". However, it doesn't seem to be working as intended. const filteredOrganizations = context.allOrganizations ...

List of null variables

I'm having trouble grasping the concept of an array filled with empty values like this: let arr=[,,,]; When I attempt to log the length, it shows 3 instead of 4. let arr=[,,,]; console.log('length',arr.length); console.log('arr[1]&a ...