简体   繁体   中英

How to change text color in drop down menu for element that is created with append()?

I'm looking for something in JQuery that can change the color of the element based on the value. I have my drop down populated dynamically, before I append my value to drop down I have if statement that checks for the value, if value is equal to 1 I want to change the color of that element if not leave it as it is. Here is my code:

for(var i=0; i < myArray.length; i++){
    if(myArray[i].idFour == '1'){
        $('#users').append('<option value='+myArray[i].idOne+'>'+myArray[i].idTwo+'</option>');
        $('#users option').css('color','red');
        }else{
            $('#users').append('<option value='+myArray[i].idOne+'>'+myArray[i].idTwo+'</option>');
        }
} 

Code above is changing color for all elements starting at the top of the drop down all the way down to the element that actually should be in red. My question is why all elements before are in red? How I can get text color in red only for elements with value 1 from myArray[i].idFour? If anyone can help please let me know. Thank you.

As @Mottie mentioned, you better create a string and append it to DOM once:

var optionList = $();
for(var i=0; i < myArray.length; i++){
    var option = '<option ';
    if(myArray[i].idFour == '1'){
        option += 'style="color:red" ';
    }
    option += 'value="'+myArray[i].idOne+'">'+myArray[i].idTwo+'</option>';
    optionList = optionList.add(option);
} 
$('#users').append(optionList);

Here is jsFiddle

You can simply add a class to option tag that you want color. So code will seem like this:

for(var i=0; i < myArray.length; i++){
  if(myArray[i].idFour == '1'){
    $('#users').append('<option class="redColor" value='+myArray[i].idOne+'>'+myArray[i].idTwo+'</option>');
  }
  else{
    $('#users').append('<option value='+myArray[i].idOne+'>'+myArray[i].idTwo+'</option>');
  }
}

And create a css class .redColor in your css stylesheet:

.redColor {
  color: red;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM