views:

71

answers:

2

I have n drop-downs like this:

<select id="select1">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<select id="select2">
 <option>1</option>
 <option>2</option>
 <option>3</option>
</select>

with identical options. All the choices should be unique, so once the option is selected in one combobox, it should be removed from others. So, if a user selects "1" in select1 there will be only options "2" and "3" in select2.

Now, http://stackoverflow.com/questions/877328/jquery-disable-select-options-based-on-radio-selected-need-support-for-all-brows offers a nice solution, but how can I modify this to work with selects instead of radio buttons?

+1  A: 

Is this what you mean?

This would remove everything from #select2 that was in #select1:

$("#select2 option").each(function() {
    if($("#select1 option[value=" + this.value + "]").length)
        $(this).remove();
});

Here's another alternative that removes all duplicates:

$("select").each(function() {
  var select = $(this);  
  select.children("option").each(function() {
    $('select').not(select).children("option[value=" + this.value + "]").remove();
  });
});

This removes every duplicate, leaving he option only in the first <select> it found it in.​

Update for your comment:

$("#select1").change(function() {
 $("#select2 option[value=" + $(this).val()+ "]").remove();
});
Nick Craver
Thanks, but I only need to remove the selected element. So, if user selects "1" in select1 there will be only options "2" and "3" in select2.
Lapa
@Lapa - Added an option for that, you can see it working here: http://jsfiddle.net/tdKUP/
Nick Craver
+1 Deleted my answer as yours covers it pretty well :) But I think in your alternative approach you should also use `change` instead of `each`
Felix Kling
@Felix - I think it's a progressive drop down situation, pick 1, then pick another, etc. I could be wrong of course, just going off Lapa's comment. I'm a bit distracted, having fun with this question currently: http://stackoverflow.com/questions/2566536/looking-for-a-jquery-plugin-to-resize-expand-browser-if-too-small :)
Nick Craver
Nick, you're right. Thank you for the answer.
Lapa
A: 

Alternatively, if the selects have the same options in the same order.

$('select').change(function() {
    var selectedIndex = $(this).find(':selected').index();    
    $('select').not(this).find('option:nth-child(' + selectedIndex + ')').remove();
)};

I think this way is faster (but less easy to read).

Alistair
This doesn't work like you think :) Once you remove the first element, the order is no longer the same, and your index is off :)
Nick Craver
Fair point.. Ok if you use it once though.. :)
Alistair