On 2008-05-01, Thomas 'PointedEars' Lahn <Po*********@web.dewrote:
Patrick Nolan wrote:
>I am using javascript to manipulate optgroups in select elements.
When the results are displayed in Firefox 2.0 there is an
annoying blank line at the top of the multi-line select box.
This doesn't happen with IE7.
There's a little program below which illustrates the problem.
I create two multi-line select boxes. The first one has an
optgroup and an option specified in the HTML. That one displays
with "opt1" as the first line. The second select is populated
using appendChild(). As far as I know the results should be
the same.
Can anyone explain this?
[...]
var theSel = document.getElementById("select2");
var optGrp = document.createElement("optgroup");
optGrp.label="opt2";
theSel.appendChild(optGrp);
[...]
<select size=8 id=select2>
</select>
Try <http://validator.w3.org/#validate_by_input+with_optionsfor a start.
WFM if the `select' element is dynamically generated as well.
OK. I learned that any SELECT element created in HTML must contain at
least one OPTION. So I put in a dummy OPTION, intending to remove it
in my onload handler. I don't understand the result. I tried
removeFirstChild() at the beginning of the handler, but there were no
OPTION elements to find at that point.
Finally I found a kluge that works. I add the new OPTGROUP and OPTION
in the onload handler, then removeFirstChild twice to get rid of the
dummy OPTION. This produces the desired effect, but I certainly don't
know why. The new script is below.
By the way, I figured out how to install the Firefox DOM inspector.
It didn't help. In the first version of the script, it showed a #text
element (with no content) before the OPTGROUP in both SELECTs. There
was no clue why Firefox should handle them differently.
--------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>Select element with blank line</title>
<script type="text/javascript">
function addOpt() {
var theSel = document.getElementById("select2");
var optGrp = document.createElement("optgroup");
optGrp.label="opt2";
theSel.appendChild(optGrp);
var item = new Option();
optGrp.appendChild(item);
item.value = "bar";
item.text = "bar";
theSel.removeChild(theSel.firstChild);
theSel.removeChild(theSel.firstChild);
}
</script>
</head>
<body onload="addOpt();">
<select size=8 id=select1>
<optgroup label=opt1>
<option value="foo">foo
</optgroup>
</select>
<select size=8 id=select2>
<option value="bar">bar
</select>
</body>
</html>