Bug in Safari: options.length = 0; not working as expected in Safari 4

Posted by Stefan on Stack Overflow See other posts from Stack Overflow or by Stefan
Published on 2010-03-12T11:16:58Z Indexed on 2010/03/12 11:17 UTC
Read the original article Hit count: 213

Filed under:
|

This is not a real question, but rather an answer to save some others the hassle of tracking this nasty bug down. I wasted hours finding this out.

When using options.length = 0; to reset all options of a select element in safari, you can get mixed results depending on wether you have the Web Inspector open or not. If the web inspector is open you use myElement.options.length = 0; and after that query the options.length(), you might get back 1 instead of 0 (expected) but only if the Web Inspector is open (which is often the case when debugging problem like this).

Workaround:

Close the Web Inspector or call myElement.options.length = 0; twice like so:

myElement.options.length = 0;
myElement.options.length = 0;

Testcase:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Testcase</title>
<script type="text/javascript" language="javascript" charset="utf-8">
function test(el){
 var el = document.getElementById("sel");
 alert("Before calling options.length=" + el.options.length);
 el.options.length = 0;
 alert("After calling options.length=" + el.options.length);
}
</script>
</head>
<body onLoad="test();">
<p>
Make note of the numbers displayed in the Alert Dialog, then open Web inspector, reload this page and compare the numbers.
</p>

<select id="sel" multiple>
 <option label="a----------" value="a"></option>
 <option label="b----------" value="b"></option>
 <option label="c----------" value="c"></option>
</select>
</body>

</html>

© Stack Overflow or respective owner

Related posts about safari

Related posts about JavaScript