1

I have 3 selects with a couple of options. When an option is changed I want to check all of the other selects, whether they are also selected or not (selected="selected"). All of the selects are in the same form.

So far I have the following javascript to do that

$("#form").change(function(event){  
 $(this).find("select").each(function(){
    alert( $(this+"option:selected").length );
 });
});

Basically following this approach: Check if option is selected with jQuery, if not select a default

The alert doenst seem to give me 1 or 0 based on the individual $(this) select element, but strangely counts up to 2 (alerts 3 times 2 after the last select is selected. After the first select it alerts 3 times 0, after the second 3 times 1, and 3 times 2 on the last). I want it to alert for example 0 0 0, then 1 0 0 then 1 0 1 and finally 1 1 1.

Any idea how this comes and how to accomplish the wanted? thx.

Community
  • 1
  • 1
Björn
  • 12,587
  • 12
  • 51
  • 70

2 Answers2

3

Your inner selector is incorrect. It should be:

$(this).find("option:selected").length

You can't prepend a dom element to a selector (since they are not strings). You'll end up with a selector that looks something like "Object objectoption:selected" since it will implicitly call the .toString() method as it is being used with the dual purpose + operator.

jQuery selectors need to be well-formed CSS3 selectors.

karim79
  • 339,989
  • 67
  • 413
  • 406
1

this+"option:selected" is not a valid selector. Try:

$(this).find("option:selected").length
JAAulde
  • 19,250
  • 5
  • 52
  • 63