Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove options from select element using jquery?

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, jQuery disable SELECT options based on Radio selected (Need support for all browsers) offers a nice solution, but how can I modify this to work with selects instead of radio buttons?

like image 817
Nikolay Lapitskiy Avatar asked Feb 27 '23 06:02

Nikolay Lapitskiy


1 Answers

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();
});
like image 165
Nick Craver Avatar answered Mar 05 '23 16:03

Nick Craver