I have a dropdown as seen below:
<select id="models" onchange="removeElements()">
<option id = "remove" value="0">R8</option>
<option id = "remove" value="1">Quattro</option>
<option id = "remove" value="2">A6 hatchback</option>
</select>
How would I create the script removeElements()
that would remove all of the options within the select?
This question is related to
javascript
jquery
html
select
In case .empty() doesn't work for you, which is for me
function SetDropDownToEmpty()
{
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");
}
$(document).ready(
SetDropDownToEmpty() ;
)
Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-
var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}
You can either use .remove() on option elements:
.remove() : Remove the set of matched elements from the DOM.
$('#models option').remove(); or $('#models').remove('option');
or use .empty() on select:
.empty() : Remove all child nodes of the set of matched elements from the DOM.
$('#models').empty();
however to repopulate deleted options, you need to store the option while deleting.
You can also achieve the same using show/hide:
$("#models option").hide();
and later on to show them:
$("#models option").show();
Try this
function removeElements(){
$('#models').html("");
}
function removeElements(){
$('#models').html('');
}
Other approach for Vanilla JavaScript:
for(var o of document.querySelectorAll('#models > option')) {
o.remove()
}
Source: Stackoverflow.com