javascript - jQuery: Change select background with content change -
i have following select:
<select class="state"> <option value="1">done</option> <option value="2">closed</option> <option value="2">open</option> <option value="2">working on it</option> <option value="2">waiting</option> </select>
the following script changing color depending of content:
$('.state option:selected').each(function(){ var state = $(this).text(); if(state == 'open') { $(this).parent().parent().css('background-color', '#e74c3c'); } else if(state == 'working on it') { $(this).parent().parent().css('background-color', '#f1c40f'); } else if(state == 'closed') { $(this).parent().parent().css('background-color', '#c0392b'); } else if(state == 'waiting') { $(this).parent().parent().css('background-color', '#d35400'); } else if(state == 'done') { $(this).parent().parent().css('background-color', '#27ae60'); } else { $(this).parent().parent().css('background-color', '#bdc3c7'); } }); $('select').change( function (){ var color = $('option:selected',this).css('background-color'); $(this).css('background-color',color); } ).change();
but script not doing: not changing color if change value of select. additionally sure, code shorter.
the select has class because select appear more once on single page.
- use addclass , removeclass
- use data-* set class add
- set style in class
- remove class before adding class of selected option
$('.state').change(function() { $(this).parent().parent().removeclass("default done closed open working waiting"); var state = $("option:selected", this).attr("data-class"); $(this).parent().parent().addclass(state); }).change();
.done { background-color: #27ae60; } .closed { background-color: #c0392b; } .open { background-color: #e74c3c; } .working { background-color: #f1c40f; } .waiting { background-color: #d35400; } .default { background-color: #bdc3c7; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div> <select class="state"> <option value="1" data-class="done">done</option> <option value="2" data-class="closed">closed</option> <option value="2" data-class="open">open</option> <option value="2" data-class="working">working on it</option> <option value="2" data-class="waiting">waiting</option> </select> </div> </div>
Comments
Post a Comment