1

I'm trying to change the background color of the current selected option of a Select. Seems simple enough using

$("#selection option:selected").css("background-color", "pink");

in jQuery onLoad. Only problem is that you cannot see the pink option until you click on the select.

I need it so that the current option is highlighted onLoad for my form.

$("#selection").css("background-color", "pink");

does achieve this, but then it highlights all other options in the select too.

https://jsfiddle.net/0h3c54Lw/1/ is an example to play around with. Are there any non-hacks to achieve this?

user2402616
  • 1,434
  • 4
  • 22
  • 38

2 Answers2

2

First you can assign "" to all options then you can assign background-color to the selected item. You can use change() event to color selection.

Try this:

$( document ).ready(function() {
    $("#selection option:selected").css("background-color", "pink");
});

$("#selection").change(function(){
    $("#selection option").css("background-color", "");
    $("#selection option:selected").css("background-color", "pink");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selection">
  <option>foo</option>
  <option>bar</option>
  <option>fizz</option>
  <option>buzz</option>
</select>
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
  • I need the default option to be pink. I.e. it should be pink when I click on "Run code snippet". Is there any way to achieve this? – user2402616 Dec 29 '19 at 03:31
  • Default means it `food` should be pink?? Because as I can see in selection box it's already pink when you click on it. – Saurabh Agrawal Dec 29 '19 at 03:47
  • Yeah, but is there any way to have it show as pink without clicking on it? That's what I mean by default. I've found the only way is to change the bg color of the select itself. However, this then changes the bg color of all the options when you then click on it – user2402616 Dec 29 '19 at 04:02
  • You can handle it dynamically so whenever option is food then only change bg color. – Saurabh Agrawal Dec 29 '19 at 04:12
  • Sure, but was hoping there'd be a more innate way to do it with css – user2402616 Dec 29 '19 at 04:17
2

I updated the jsfiddle to more accurately describe the behavior I was looking for (sorry for confusion, this was a tough problem to describe)

https://jsfiddle.net/fzjv2ry4/2/

$("#selection").css("background-color", "pink");
$("#selection > option").css("background-color", "white");
$("#selection option:selected").css("background-color", "pink");

I simply first set the bg color of the whole select. Then all its options to white, and then finally the selected one to pink again. This isn't a non-hacky solution I was looking for, but it does work. Any other simplifications or better ideas using css would be greatly appreciated

user2402616
  • 1,434
  • 4
  • 22
  • 38