Reputation: 13763
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.
Upvotes: 47
Views: 185705
Reputation: 662
You may have select option values such as "Choose option". If you want to keep that value and clear the rest of the values you can first remove all the values and append
"Choose Option"
<select multiple='multiple' id='selectName'>
<option selected disabled>Choose Option</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Jquery
$('#selectName option').remove(); // clear all values
$('#selectName ').append('<option selected disabled>Choose Option</option>'); //append what you want to keep
Upvotes: 0
Reputation: 566
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
Upvotes: 0
Reputation: 3241
Here is a small jQuery plugin that (among other things) can empty an dropdown list.
Just write:
$('your-select-element').selectUtils('setEmpty');
Upvotes: 0
Reputation: 54084
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();
Upvotes: 99
Reputation: 595
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);
Upvotes: 1