Reputation: 73
With this html:
<div class="outer">
<div class="inner">
<span class="selection" title="Green"></span>
</div>
<div class="inner">
<span class="selection" title="Yellow"></span>
</div>
<div class="inner">
<span class="selection" title="Red"></span>
</div>
</div>
and this existing jQuery which can be changed as necessary:
$(document).ready(function(){
$('.outer .inner span.selection').each(function(){
if($(this).attr('title', 'Green')) {
$(this).parent().css('background-color', 'green');
}
if($(this).attr('title', 'Yellow')) {
$(this).parent().css('background-color', 'yellow');
}
if($(this).attr('title', 'Red')) {
$(this).parent().css('background-color', 'red');
}
});
});
Essentially this only displays a single item in a dropdown. I'm looking to change the list item displayed as a single color. Other list items that aren't selected are hidden.
Upvotes: 1
Views: 60
Reputation: 911
Hi im not exactly sure what you mean with your question. But are you trying to get individual color put as the background for the sections, instead of just the last color that it checks for?
You need to set the value to what equals the title instead of comparing it. I fixed it in this code pen: http://codepen.io/anon/pen/eJeKgZ
$(document).ready(function(){
$('.outer .inner span.selection').each(function(){
if($(this).attr('title') == 'green') {
$(this).parent().css('background-color', 'green');
}
if($(this).attr('title') == 'yellow') {
$(this).parent().css('background-color', 'yellow');
}
if($(this).attr('title') == 'red') {
$(this).parent().css('background-color', 'red');
}
});
});
Upvotes: 1
Reputation: 510
You are setting the value to the title and not comparing, try this:
$(document).ready(function() {
$('.outer .inner span.selection').each(function() {
var title = $(this).attr('title');
console.log(title);
if (title === 'Green') {
$(this).parent().css('background-color', 'green');
}
if (title === 'Yellow') {
$(this).parent().css('background-color', 'yellow');
}
if (title === 'Red') {
$(this).parent().css('background-color', 'red');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="outer">
<div class="inner">
<span class="selection" title="Green">Green</span>
</div>
<div class="inner">
<span class="selection" title="Yellow">Yellow</span>
</div>
<div class="inner">
<span class="selection" title="Red">Red</span>
</div>
</div>
Upvotes: 2