Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone <select> without the selected value of the first <select>

I have two dropdowns on my website.

The first one is being populated using an ajax call to my database which returns some json.

I would like the second one to be an exact copy of the first one, but with one option less: the option that is selected in the first dropdown.

Is there a convenient way to do this within jQuery?

Here's what I tried so far:

$('#first').find('option').clone().find('option:selected').remove().end().appendTo('#second');

but this only clones it, without removing the selected option.

Any help is much appreciated!

like image 333
binoculars Avatar asked Oct 24 '25 04:10

binoculars


2 Answers

You can filter out the selected option using the not() method and then append the cloned collection to the second dropdown:

$('#first option').not(':selected').clone().appendTo('#second');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
  <option>1</option>
  <option selected>2</option>
  <option>3</option>
</select>

<select id="second"></select>
like image 52
31piy Avatar answered Oct 26 '25 18:10

31piy


You could simply use filter() after appending the clone to new node like :

$('#first option').clone().appendTo('#second').filter(":selected").remove();

See below snippet :

$('#first option').clone().appendTo('#second').filter(":selected").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
  <option>One</option>
  <option>Two</option>
  <option selected >three</option>
  <option>Four</option>
</select>

<select id="second">
</select>
like image 43
Spring Avatar answered Oct 26 '25 18:10

Spring