Issue
I have a form that contains a select
with several options
. One option
can be selected by default based on a value in the DB.
If an option is selected by default, we want to apply some styling to it.
Once the form is rendered, I can simply do something like this...
$('#mySelect option:selected').addClass('customClass');
Lets say customClass
just makes background-color:green
.
What happens is that once the form is loaded, the option is still default white in the select. It only turns green once you click on the select.
I think this is because only the option is being changed to green.
If I do, just $('#mySelect').addClass('customClass');
then all options are green.
I thought about applying the class to the whole select and then looping through all options and removing the class except for the selected one, but that doesn't seem efficient.
Any ideas of a concise way to do this?
Thanks!
Here's a simple example almost working example
Solution
Working Demo: https://jsfiddle.net/o81hyseg/
$("#mySelect").on("change", function(e){
if(!e.isTrigger)
$(this).find("option").removeAttr("selected");
if($("#mySelect").val() == "green"){
$('#mySelect').addClass('foo');
$('#mySelect').attr('title', 'foo');
$(this.options[this.options.selectedIndex]).attr("selected","");
}
else{
$('#mySelect').removeClass('foo');
$('#mySelect').removeAttr('title', 'foo');
}
});
$("#mySelect").trigger("change");
.foo {
background-color: green;
}
.foo option:not([selected]) {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">Select...</option>
<option>white</option>
<option>white</option>
<option>white</option>
<option selected>green</option>
<option>white</option>
</select>
Answered By - Nikhil Parmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.