简体   繁体   中英

Unable to add same option element to more than one dropdown

I have two dropdowns on a page. When a button is clicked I need a new option to be added to both dropdowns (same option to be added to both). The option values are stored in an array, I first create a new option element new_option and set its value/text from the array, and then the option gets added to the dropdown with dropdown1_name.options.add(new_option) and dropdown2_name.options.add(new_option) .

But in practice, the new option gets added only to the second dropdown I add it to but not the first, ie if I do dropdown2.add followed by dropdown1.add then only dropdown1 gets the new option.

It is easy to fix this by creating a replica of the new option element from scratch, and adding one copy to each dropdown. But that doesn't make sense to me so the point of this question is I would really like to understand what causes this behavior in the first place. Why can't the same newly created option be added to both dropdowns??

This fiddle I just made has a test setup.

The problem is you are adding the same <option> instance to both dropdowns:

dropdown2.options.add(el1);
dropdown1.options.add(el1);
//                    ^^^ notice "el1" twice

Instead, you have to add el2 to dropdown2 :

dropdown2.options.add(el2);
dropdown1.options.add(el1);

I hope this helps you:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM