Home >Web Front-end >HTML Tutorial >A bug fix for the optGroup tag in the HTML drop-down box
When the first item in the drop-down box is optGroup, when using the mouse wheel to change the option, if you scroll up quickly, the first item optGroup will be selected. This is not the result we want, and If you use code to get the value of the drop-down box, an error will occur.
After selecting optGroup, the value of selectIndex is still 0 after the drop-down box loses focus (when there are options in the drop-down box). The value of selectIndex is only true when the drop-down box gains focus again and loses focus. becomes -1, so simply judging the selectIndex in onblur is not possible, so we need to do an intermediate process, and then judge the selectIndex. If the optGroup is selected, set the selectIndex to 0.
When the drop-down box only has optGroup, no item is selected by default, that is, an empty item. The selectIndex of an empty item is also -1, so in this case you cannot directly set the selectIndex to 0 (because there is no option item) , I can't set it to -1, that will have no effect. We need to first add an option to the drop-down box, set selectIndex to 0, then set selectIndex to -1, and then add the newly added option Delete , because in principle optGroup cannot be selected, so when selectIndex is set to -1, an empty item will be selected.
The specific code is as follows:
<HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <SELECT id="sel" onblur="ValidateElement(this);"> <optgroup label='1111'> </optgroup> </SELECT> <SELECT id="sel1" onblur="ValidateElement(this);"> <optgroup label='1111'> <option >12</option > <option >23</option > <option >34</option > </optgroup> <option >aa</option > <option >bb</option > <option >cc</option > </SELECT> </BODY> </HTML> <SCRIPT LANGUAGE="JavaScript"> <!-- function ValidateElement(obj) { var t = obj.selectedIndex; obj.selectedIndex = -1; obj.selectedIndex = t; if(obj.selectedIndex == -1) { if(obj.options.length > 0) { obj.selectedIndex = -1; obj.selectedIndex = 0; } else { opt = document.createElement("option"); opt.innerText = ""; obj.insertAdjacentElement("beforeEnd",opt); obj.selectedIndex = 0; obj.selectedIndex = -1; try { obj.options[0] = null; } catch(e){} } } } //--> </SCRIPT>
The above is the detailed content of A bug fix for the optGroup tag in the HTML drop-down box. For more information, please follow other related articles on the PHP Chinese website!