user3023588 user3023588 - 5 months ago 7
HTML Question

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.

Answer

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);
Comments