Joe
Joe

Reputation: 442

Bugs coloring certain options of multiselects with jQuery

I'm trying to color in red some options of my multiselect lists while filling them, using jQuery. Here's my code:

$.each(subjects, function(key, subject) 
{
    if (select.find('option[value=\"' + encodeURIComponent(subject) + '\"]').length === 0 && subject!="") 
    {
        //Ajouter la nouvelle catégorie dans la liste
        $('<option>', {
            value: subject,
            text: subject
        }).appendTo(select);
                 
        if (colored==true)
        {
            //Change color of options' text

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

I currently have two problems with this code:

1- the second encodeURIComponent is not working to deal with options containing simple quotes. Here's an example of error in console:

Uncaught Error: Syntax error, unrecognized expression:

value='est%20le%20type%20d'action%20de']

I tried modifying the line where this happens to make it like the one in the first if clause, but it didn't change anything.

2- My jQuery code does not color the options that contain spaces.

How can I solve both of these issues? Thank you in advance.

Edit: variable selectList contains the name of my multiselect.

Upvotes: 1

Views: 221

Answers (1)

Shauna
Shauna

Reputation: 9596

Don't use spaces or quotes in your options. (AKA - "Don't do that") Instead, consider using a key (either numeric or simple text) for the value of your options. When you handle the input, you can then map those values to what you really need. Doing this may also save your HTML at some point, by preventing you from accidentally putting in a character that closes the attribute, or even the whole tag.

Invert your quotes. JavaScript can use '' or "" for strings. If you can't get around having single quotes, and know that you won't use double quotes in your option values, then replace this:

" option[value='"+ encodeURIComponent(subject) +"']"  

with this:

' option[value="'+ encodeURIComponent(subject) +'"]'

Don't URI Encode the values when putting them into the HTML Instead, leave the values plain, or if you need to, try HTML encoding them. If you need them URI encoded (such as for GET parameters), then URI encode them on form submit, just as you're getting ready to send the data elsewhere.

Upvotes: 1

Related Questions