0

I want jQuery to change the color of some of my multi-select list's options to red, if a certain condition is selected. Here's my code:

$.each(subjects, function(key, subject) 
        {
            if (select.find('option[value=\"' + encodeURIComponent(subject) + '\"]').length === 0 && subject!="") 
            {
                   $('<option>', {
                     value: subject,
                     text: subject
                     }).appendTo(select);

                 if (colored==true)
                     {
                         //Change color of options' text
                         $("option[value='"+subject+"']").css('color', 'red');
                     }
            }
        });

The problem with this code, is that jQuery colors to red not only the options of the current multi-select on which it is working, which's name is defined in variable select. But jQuery also colors these options in all other multi selects on the page, if they contain it.

How to edit this code to make jQuery only color the option contained in the current multi-select, which's name is, again, defined in the select variable?

For instance, replacing

$("option[value='"+subject+"']").css('color', 'red');

with

(select.find("option[value='"+subject+"']").css('color', 'red');

did not work. What would be the correct code? Thank you in advance.

3
  • Where is the select variable coming from anyway? Jan 3, 2013 at 20:06
  • The code given above is in a function. Here's how the function begins: changeList = function(data, selectList, colored, emptyList) { var subjects = data.split(','); var select = $('#'+selectList); [...]
    – Joe
    Jan 3, 2013 at 20:08
  • 1
    Your solution looks like it SHOULD work. Something else must be going on. Can you build us a working fiddle so we can see it failing? Jan 3, 2013 at 20:11

1 Answer 1

0

Did you try?

$("#" + selectList + " option[value='"+ encodeURIComponent(subject)+"']").css('color', 'red');

LMM - Edited to include the encode

2
  • @Blazemonger That's a pretty obvious mistake. Fixed it now.
    – Lee Meador
    Jan 3, 2013 at 20:18
  • @Blazemonger I have another question about this: my code does not paint in red options containing spaces. How can I solve this please? (I can't reach Lee Meador with @ tag...)
    – Joe
    Jan 4, 2013 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.