The following HTML Markup consists of an HTML DropDownList (DropDown) control and a Button. When the Button is clicked, the Reset JavaScript function is executed. Inside this function, the SelectedIndex property of the DropDownList is set to 0 (First Item).
You can clear the selected item in the below two different ways. By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction. By using showClearButton property, you can enable the clear icon in DropDownList element.
To remove all options from a select list using jQuery, the simplest way is to use the empty() method.
To remove the options of an HTML element of select
, you can utilize the remove()
method:
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
// using the function:
removeOptions(document.getElementById('DropList'));
It's important to remove the options
backwards; as the remove()
method rearranges the options
collection. This way, it's guaranteed that the element to be removed still exists!
If you wish to have a lightweight script, then go for jQuery. In jQuery, the solution for removing all options will be like:
$("#droplist").empty();
Probably, not the cleanest solution, but it is definitely simpler than removing one-by-one:
document.getElementById("DropList").innerHTML = "";
This is the best way :
function (comboBox) {
while (comboBox.options.length > 0) {
comboBox.remove(0);
}
}
You can use the following to clear all the elements.
var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
select.options[i] = null;
}
This is a short way:
document.getElementById('mySelect').innerText = null;
One line, no for, no JQuery, simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With