Search code examples
jquerycssdrop-down-menuhtml-select

Change color in drop-down where jquery change multiply drop-down-menu


I use a jquery to change multiply drop-down-menus with one selection. And I use one drop-down-menu to do the change for all the others.

I added diffrent background color to each option. And when I change an option on the drop-down-menu that contral them all that backround color won't be displayed on the other drop-down-menus.

How can I achive this?

Heres the jquery

function addMessage(msg, clear){
      if (clear !== null && clear) {
          $('#msgs').html("");
      }
      $('#msgs').append(msg+"<br/>");
  }

  function onSelectChange(){
      var stext = $("#s_make option:selected").val();
      addMessage("you selected: " + stext);
      switch (stext) {
      case "opt_1":
          $("#s_score > option[value='xml_multi_01.php']").attr('selected','selected');
          break;
      case "opt_2":
          $("#s_score > option[value='xml_multi_02.php']").attr('selected','selected');
          break;
      case "opt_3":
          $("#s_score > option[value='xml_multi_03.php']").attr('selected','selected');
          break;
      case "opt_4":
          $("#s_score > option[value='xml_multi_04.php']").attr('selected','selected');
          break;
      }
  }


  function init(){
      addMessage("init()<br/>");
      $("#s_make").change(onSelectChange);
  }

  // keep this if using jQuery
  $(document).ready(init);

And heres the html

<select id='s_make' onChange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
    <option value='--' style="background: #ffffff;">Change all options to... </option>
    <option value='opt_1' style="background: #bfe29c;">Option 1</option>
    <option value='opt_2' style="background: #9cc474;">Option 2</option>
    <option value='opt_3' style="background: #b6dafb;">Option 3</option>
    <option value='opt_4' style="background: #6cace8;">Option 4</option>      
  </select>



Option 1Option 2Option 3Option 4

Option 1Option 2Option 3Option 4

Take a look at this jsfiddle and you will propably see what I mean: http://jsfiddle.net/mqw9c88d/


Solution

  • There is a number ways of achieving that, for example you can update color of other select's once you changed your 'main' select:

    function onSelectChange(){        
        $("#s_score").css('backgroundColor', this.style.backgroundColor);
        //other code...
    }
    

    See partially working JsFiddle (it changes color only of 2nd select because you have same id for 2nd and 3rd selects)