w3resource

jQuery: Remove all the options of a select box and then add one option and select it

jQuery Practical exercise Part - I : Exercise-15

Using jQuery remove all the options of a select box and then add one option and select it.

Sample solution :

HTML Code :

<!DOCTYPE html>
  <html>
  <head>
  <script src="https://code.jquery.com/jquery-git.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Remove all the options of a select box and then add one option and select it with jQuery</title>
  </head>
  <body>
  <select id='myColor'>
  <option value="Red">Red</option>
  <option value="Blue">Blue</option>
  <option value="Green">Green</option>
  </select>
<input type="button" value="Click to Remove all Options" onclick="Remove_options()"/>
  </body>
  </html>

JavaScript Code :

function Remove_options()
{
$('#myColor')
    .empty()
    .append('<option selected="selected" value="test">White</option>');
}

See the Pen jquery-practical-exercise-15 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Add a list elements within an unordered list element using jQuery.
Next: Underline all the words of a text using jQuery.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/jquery-exercises/part1/jquery-practical-exercise-15.php