Skip to content
Advertisement

Sort Option children by index value for both parent Selects (Javascript Only)

I’m trying to create a Dual List Box using only vanilla Javascript, no JQuery or JS packages, for learning purposes.

When a user double-clicks an Option, that Option appends to the other parent Select (boxB) and is removed from the original parent Select (boxA), and vice versa. The Option elements have data-index attributes with ascending numerical values. How do I maintain the numerical order of the Options by index value, regardless of which parent Select they append?

JavaScript

Advertisement

Answer

Since you are basically using the same logic for both selects, I consolidated into one function. Rather than use ID’s, which can be problematic, we can use a single className and rely on basic JS to determine which is which. The sorting mechanism – your original question – works by taking all the option elements into an array, sorting the array by dataset.index, and then repopulating the select element. One set of logic works for both boxes

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement