Scott B
Scott B

Reputation: 40157

Can jQuery each() be used to modify each item(option) in a select list?

Given this select list:

<select id="my_list">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>

I'd like to do a jQuery that iterates over each of the option items and changes it to disabled when a certain condition of my each() statement is met.

I'm trying this (just as a test):

$('#my_list').each(function(){
    alert('test');
    if($(this).val()=='two')){
        $(this).css('background-color':'gray','padding':'10px');
    }
});

But the alert never fires to tell me its iterating over the values of the option list.

Upvotes: 1

Views: 965

Answers (3)

ButtersB
ButtersB

Reputation: 514

$('my_list span').each(function(i,item){...}

From there you have access to increment via i, or the $(this), which is redundant, and unnecessary.

Upvotes: 0

Michael
Michael

Reputation: 4090

Couple of things here. That doesn't match an element with id of my_list, and it certainly doesn't match the options. This does:

$("#my_list").children()

Try something like the following to hide them:

$("#my_list").children().each(function() {$(this).wrap("<span>").hide();});

And the following to un-hide everything:

$('#my_list span').each(
    function () {
        var opt = $(this).find("option").show();
        $(this).replaceWith(opt);
    }
);

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237847

The first problem is that you need a # in your selector:

$('#my_list');

The second is that you need to select the option elements, not the select:

$('#my_list option')

The third problem is that you can't reliably style option and select elements anyway.


NB that you could achieve the code above by putting the value check into the selector:

$('#my_list option[value="two"]').css(...);

Upvotes: 5

Related Questions