How do you remove all the options of a select box and then add one option and select it with jQuery?
-
07-10-2020 - |
سؤال
How do you remove all the options of a select box and then add one option and select it with jQuery?
To remove, use remove() and append() to add option in already created select list. Let’s say the following is our select −
<select id="demo"> <option value="JavaScript">JavaScript</option> <option value="MySQL">MySQL</option> </select>
Example
Following is the code to remove all the options and add a new one −
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <select id="demo"> <option value="JavaScript">JavaScript</option> <option value="MySQL">MySQL</option> </select> </body> <script> $('#demo') .find('option') .remove() .end() .append('<option value="MongoDB">MongoDB</option>') .val('MongoDB') ; </script> </html>
To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor.
Output
The output is as follows −
Advertisements
لا تنتمي إلى Tutorialspoint