Logo

How do you remove all the options of a select box and then add one option and select it with jQuery?

Below is a straightforward approach to clear out existing options from a <select> box and then add a single option, making sure it’s also selected.

$(document).ready(function() { var $selectBox = $('#mySelect'); // 1) Remove all existing options $selectBox.empty(); // 2) Create a new option var newOption = $('<option>', { value: 'option1', text: 'My New Option' }); // 3) Append it to the select box $selectBox.append(newOption); // 4) Select the newly added option $selectBox.val('option1'); });

What’s Happening Here?

  1. $selectBox.empty(): Removes any child <option> elements from the <select>.
  2. $('<option>', { ... }): Dynamically creates a new <option> element, setting both its value and display text.
  3. .append(newOption): Inserts the new <option> into the <select>.
  4. .val('option1'): Updates the <select> to show the new option as selected.

Best Practices

  • Use .empty() or .html('') to clear options before adding new ones.
  • Set .val(...) to the exact value of the newly added option to ensure it’s actually selected.
  • Handle Edge Cases: If you have logic for multiple new options, or you’re fetching them from an API, ensure you sanitize or validate that data before appending.

Level Up Your JavaScript Fundamentals

If you’d like to deepen your understanding of JavaScript, jQuery, and DOM manipulation, consider:

And for those aiming to succeed in competitive tech interviews, Grokking the Coding Interview: Patterns for Coding Questions is an invaluable resource, focusing on the problem-solving patterns often tested at FAANG and other big tech companies.

Lastly, if you’re seeking personalized feedback and a genuine interview simulation, Coding Mock Interviews at DesignGurus.io offer one-on-one sessions with ex-FAANG engineers, helping you refine your coding strategies and communication skills.

CONTRIBUTOR
TechGrind