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!
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With