In my HTML, I have a <select> with many <option> elements. I want to use jQuery to check each option's value against a Javascript variable. If one matches, I want to set a color of that option. How would I do that?
            Asked
            
        
        
            Active
            
        
            Viewed 84 times
        
    -2
            
            
         
    
    
        Rory McCrossan
        
- 331,213
- 40
- 305
- 339
 
    
    
        Yao
        
- 1
- 
                    3show us what you have tried so far. – Kevin Kloet Nov 21 '16 at 09:53
3 Answers
0
            
            
        If I understood from your requirement, you should try following,
var yourVar = 1; //consider your expected value;
$(document).on('change', '#selectId', function(){
   var currentValue = $(this).val();
   if(yourVar == currentValue)
   {
        //apply your colour logic
   }
});
 
    
    
        ScanQR
        
- 3,740
- 1
- 13
- 30
0
            
            
        If it's just a plain html list, not a jQuery UI one then that's all:
var found = $('#cars option[value="saab"]');//Search for 'saab' value
found.css("color","red");//Set color as red<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 
    
    
        Theodore K.
        
- 5,058
- 4
- 30
- 46
- 
                    if the value is array ,for example I want to set red for Volvo and Saab option,How should I do it using each? – Yao Nov 21 '16 at 10:36
- 
                    @Yao, one way to do that is by `$('#cars option[value="saab"],[value="volvo"]');` or check http://stackoverflow.com/questions/26301547/jquery-select-elements-by-value-from-array-of-values – Theodore K. Nov 21 '16 at 10:41
0
            
            
        You can catch which option you've selected from jquery, from the $(select).find('option:selected'), another way is the $(select).val() (It'll returns the value of select).
But to style the select element is not possible, checkout this link
 
    
    
        Community
        
- 1
- 1
 
    
    
        Nijat Ahmadov
        
- 64
- 1
- 1
- 6