views:

163

answers:

3

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"&gt;
<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>
+1  A: 

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

myElement.options.length = 0;
myElement.options.length = 0;
Stefan
+1  A: 

Can't reproduce that with current dev-channel version. 5.0.375.6

loislo
I mean in Chrome. Also it is working fine in WebKit which was built from the latest sources.
loislo
A: 

Try:

myElement.options.splice(0, myElement.options.length);

(first param is the starting index, second param indicates how many elements to delete)

ignaZ