Change the background color of a specific div with a radio button / case
I am trying to change the background color of some specific divs based on their content.
Their background color should change when their input is like "Lifestyle" or "Politics" or "Economics" or "Local" or "Sports" or "News".
var colorInput = document.getElementById('views-field-field-section').textContent;
switch (colorInput) {
case 'Lifestyle':
document.getElementById('views-field-field-section').style.backgroundColor = '#9518b8';
break;
case 'Local':
document.getElementById('views-field-field-section').style.backgroundColor = '#009fe3';
break;
case 'Sports':
document.getElementById('views-field-field-section').style.backgroundColor = '#95c11f';
break;
case 'Economy':
document.getElementById('views-field-field-section').style.backgroundColor = '#d40d10';
break;
case: 'Politics':
document.getElementById('views-field-field-section').style.backgroundColor = '#ffcc00';
break;
default:
break;
}
source to share
You cannot use IDs more than once in an html document. This will be invalid html. I changed the id to class and then used the following code and it works:
var colorInput = document.getElementsByClassName('views-field-field-section');
for(i=0; i<colorInput.length; i++) {
var colorInputText = colorInput[i].textContent.trim();
switch (colorInputText) {
case 'Lifestyle':
colorInput[i].style.backgroundColor = '#9518b8';
break;
case 'Local':
colorInput[i].style.backgroundColor = '#009fe3';
break;
case 'Sports':
colorInput[i].style.backgroundColor = '#95c11f';
break;
case 'Economy':
colorInput[i].style.backgroundColor = '#d40d10';
break;
case 'Politics':
colorInput[i].style.backgroundColor = '#ffcc00';
break;
default:
text ='Nix!';
}
}
Here is a jsfiddle: http://jsfiddle.net/gFN6r/505/
source to share
Oh man. Don't use the same id
:) But if necessary, ok ...
I have adjusted your original code a bit, eg. there was some syntax error and jQuery added, hope this is not a problem :)
-
If you use the same
id
, it won't work -$('#myid')
but it will -$('[id=myid]')
-
Remember to use the
trim
-like function to remove trailing spaces. - And think a little about how to avoid the same
id
in your code.
http://jsfiddle.net/gFN6r/506/
$('[id=views-field-field-section]').each(function() {
var text = $(this).text();
text = $.trim(text);
switch (text) {
case 'Lifestyle':
$(this).css({backgroundColor: '#9518b8'});
break;
case 'Local':
$(this).css({backgroundColor: '#009fe3'});
break;
case 'Sports':
$(this).css({backgroundColor: '#95c11f'});
break;
case 'Economy':
$(this).css({backgroundColor: '#d40d10'});
break;
case 'Politics':
$(this).css({backgroundColor: '#ffcc00'});
break;
default:
$(this).text('Nix!');
break;
}
});
source to share