De-select all html select options in a control that does not allow multiple selection
I have a web page with several HTML Select controls that all allow multiple selection. Next to each control we have a "Clear" button that de-selects all selected items in the control, with the onclick that looks something like this:
<input type=button value="Clear" size=5 onclick="selectOptions('n.MyControl', false)">
The called Javascript code looks like this:
function selectOptions(controlName, bSelectItems)
{
for (i=0; i < document.myForm[controlName].options.length; i++)
{
document.myForm[controlName].options[i].selected = bSelectItems;
}
}
It works really well with the Select controls that allo开发者_如何学运维w multiple selection, but I just added a Select control that does not allow multiple selection (i.e. does not have the "multiple" attribute), and this code does not clear it. If I add the "multiple" attribute, the Clear button starts working again, so I know it has something to do with the fact that I am not allowing multiple items to be selected.
My question is, why does the above code not work and more importantly, how can I get my new Select control cleared in JavaScript?
The reason your code doesn't work is because you are trying to iterate over each option and do something, but since (like you said) the multiple attribute isn't set, it doesn't let you modify multiple options.
As for fixing it, you can try to get the selected option and then just deselect that single option.
Update: I don't know for sure that this is the ideal solution, but it seems to work for me in IE8.
document.getElementById('myselect').selectedIndex = -1;
Of course you can get the select
element whichever way works best for you, but just set the selectedIndex
attribute to -1
.
There is no such thing as a cleared single-<select>
box. One option will always be selected as long as there are any options in the select at all. If no options have selected
set at first load time, the first option will automatically get selected.
The usual approach is to have the first option as a dummy-option like <option value="">(Please select a thing)</option>
, and reset to that (with select.selectedIndex= 0
).
精彩评论