Reputation: 1025
I'm trying to add a color to filter options in my webshop. The color codes are getting saved, now I return them through json. What i'm trying to do is add the color code to the parent class above the input. I found out how to change the class name (which i need for other reasons), but now I must add the color codes in order that json returns them top, down.
Here's what I got so far:
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 with console.log(data.colorInfo[i].colorCode); results in the 3 color codes i need #fff etc. Is there a way to insert each of the results above the 3 input types i have?
What i would like to achieve is:
<div style="background-color: data.colorInfo[i].colorCode"> <input> </div>
something like that
Upvotes: 0
Views: 174
Reputation: 9470
function onDataReceived(data) {
//for (var i = 0; i < data.colorInfo.length; i++) {
// console.log(data.colorInfo[i].colorCode);
//}
var len = data.colorInfo.length;
$('input[id^="filter_"]').each(function(i){
$(this).parent().addClass('addedClass');//attr('class','addedClass');
$(this).parent().parent().addClass('addedClass')
.css('background-color',"'" + data.colorInfo[i % len].colorCode + "'");
//.attr('class','addedClass');
});
}
Upvotes: 1
Reputation: 1348
I think my approach would be to get the string with the class names from the DOM element:
var classString = $(this).parent().attr('class','addedClass');
Then split it, and loop through it:
var newClasses = []; //initalize the new classes array
var classes = classString.split(/ /);
for(var a=0; a<classes.length; a++){
var colorObj = data.colorInfo[a]; //get the relevant color object
if(colorObj){
newClasses.push(classes[a] + '-' + colorObj.colorCode); //
}
}
And then replace the old classes with the newly created ones:
$(this).parent().attr('class', newClasses.join(' '));
Something like that. You might want to test it out first ;)
Upvotes: 0