clearing select using jquery
Is it possible to clear the contents of a html select object using JQuery? I have a function that gets a list to populate the select and appends it to the select, so I need some way of clearing the previous data before appending.
use .empty()
$('select').empty().append('whatever');
you can also use .html()
but note
When
.html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
alternative: --- If you want only option elements to-be-remove, use .remove()
$('select option').remove();
If you don't care about any child elements, e.g. optgroup
, you can use empty()
...
$('select').empty();
Otherwise, if you only want option
elements removed, use remove()
.
$('select option').remove();
$('option', '#theSelect').remove();
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
$("#selectListName").prop('selectedIndex', -1);