I want to be able to reset <select> tags by themselves instead of making them reset with the entire form. This is what I have so far:
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
And the JS:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
selectedOptions[i].selected = false;
}
}
When I first tried this, it seemed to work. However, only when one option is selected. I've noticed that when there is more than one option currently selected, it seems to break.
Starting with three options, and clicking the Reset button results in this, for some reason:
Every option gets deselected apart from one. Why does this happen?
Clicking the Reset button again deselects the one still selected option though.
You can set the selectedIndex attribute to -1 to indicate that no element is selected.
function resetS() {
const multipleSelect = document.getElementById('s');
multipleSelect.selectedIndex = -1;
}
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
The list of selected <option> elements is a "live" list. When you change the selected flag on one of the elements, the list changes; that is, the <option> you changed disappears from the list, so the length gets 1 shorter. An indexed for loop will therefore skip elements.
The way to deal with that (well, one way) is to use a while loop as follows:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
while (selectedOptions.length) {
selectedOptions[0].selected = false;
}
}
edit — or you could use the method suggested in Tom's answer, which is simpler.