Adding and Removing Select Options - J Query

You have a drop-down box for colors and want to add new colors to it, as well as remove options from it.


To add a new option to the drop-down box, use the .appendTo() method:

To remove an option, use the .remove() method:


I use the .attr() and .text() methods to populate the <option>element:

However, the same line could be rewritten so that the <option>element is built in onestep, without using the methods:

Concatenating all the <option>data like that would be a fraction of a millisecond faster,but not in any way noticeable by a human. I prefer using the .attr() and .text()methods to populate the <option>element because I think that it is more readable and easier to debug and maintain. With the performance issue being negligible, using one approach or the other is the developer’s preference.
What would happen with JavaScript disabled? You would need to provide a server-side alternative that processes the button clicks, and the user would have to wait for the resulting page reloads.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics