Given a select box with a fixed number of options, the task is to remove all the options and then add one option and immediately select that particular option using jQuery. There are two approaches that can be taken to achieve this:
In the following example, a select box with some options and a button element is created. The button also has an onclick attribute which means that on the button click, the script or the function specified within the attribute is executed.
We select all the options in the select box using the find() method with a parameter of “option“. Then, we remove all the selected options using the remove() method. We use the end() method to revert the selection back to the select box. To add one option, the append() method can be used. The parameter inside the append() method is a string containing HTML markup for the option to add to the select box.
Example: In the following example, a select box with 4 options is created. On button click, all the options are removed and one new option is added.
Instead of selecting all options, removing them, and then adding one option, we directly empty or remove all the children nodes of the select box. The children nodes are removed using the empty() method and then add a new option using the append() method. The parameter inside the append() method is a string containing HTML markup for the option to be added to the select box.
Please Login to comment...