How do you remove all the options of a select box and then add one option and select it with jQuery?
Strip, append, and select in a single line with jQuery:
This sweeps clean the select box with empty()
and ushers in a new selected option via new Option(text, value, selected)
.
Chain of command
Compact, readable, and maintainable. That's what chaining affords. Just look at this:
Chaining brings out the beauty of jQuery at its peak, reducing DOM trips, and making your code as snappy as a crocodile.
Juggling multiple jQuery objects
Operations on more than one element are like spinning multiple plate on sticks. Don't fret, .end()
will save your day:
Voila! It returns to the original element at the end of the execution, ensuring your jQuery object doesn't get lost in the abyss.
Entangling Internet Explorer quirks
For folks still supporting old versions of Internet Explorer, you might want to sprinkle some 'selected' attribute in the mix for good measure:
First option survivor 🏝️
Need the first option to survive the empty()
apocalypse? Use the :not
selector:
This ensures the first option remains intact while sending all the others to the valley of the forgotten.
Beyond jQuery: Vanilla to the rescue
When jQuery's too sugar-coated and you want some pure, raw vanilla JavaScript:
Use new Option()
to peel jQuery and get a clean, direct approach to crisper options.
Balance with standard DOM techniques
Some offer you the red pill, some offer the blue. Here, swallow both. Mix jQuery with standard DOM to balance out browser quirks:
DOM and jQuery, different as night & day, but together they make a perfect dawn.
Was this article helpful?