oeyvind said:
This works:
function init()
{
textfield1 = window.top.frames[2].document.getElementById("ta1");
alert("DEBUG");
textfield1.value = "";
}
This doesnt work:
function init()
{
textfield1 = window.top.frames[2].document.getElementById("ta1");
textfield1.value = "";
}
Happy now ??
Not quite. When does init() run? Are you absolutely positive that the content
of top.frames[2] has completely loaded before you call this function? If init()
runs as the window.onload event of the frame it is in, it is entirely possible
that the content of top.frames[2] is not completely loaded before it runs.
If the content of top.frames[2] is not loaded when you run this function, the
assignment to textfield1 should fail, and an alert() after the assignment
shouldn't resolve the problem, however there may be strange race conditions
within the JavaScript interpretor that allow this behaviour. Either that your
your real example places the alert() before the assignment to textfield1, in
which case it's a simple matter of the alert() providing enough of a delay to
allow top.frames[2] to load.
'There are many possible reasons why
adding an alert() might work-around a design problem.'
Like what ??
Like trying to access the content of another frame/window before it is
completely loaded. Adding alert() provides enough delay for the content of the
other frame/window to load completely.
<script type="text/javascript">
var w = window.open('somepage.html', 'someName');
// alert('DEBUG');
var textfield1 = w.document.getElementBy('ta');
textfield1.value = 'something';
</script>
The above code is almost certain to fail because somepage.html is unlikely to
be completely loaded by the time you attempt to make the assignment ot
textfield1. Uncomment the alert() however, and now the asynchronous loading of
the new window has time to finish before the script continues.
I have to admit I`ve never ever before seen a variable assigment`s success
been
dependent on a meaningless alert placed before it.
When dealing with cross-frame or multi-window scripting where things are
happening asynchronously, it is very easy to create race conditions where
things will work only with an alert(), or will work intermitantly.
The best way to deal with these situations is have each frame look after it's
own business. In other words, the frame containing the init() function
shouldn't be "reaching into" top.frames[2] to clear the value. Ideally,
top.frames[2] should clear it's own value, but if you have a reason to have it
happen from frames[0], then do something like:
-- in top.frames[2]
<body
onload="
if (top.frames[0].clearTextInput) {
top.frames[0].clearTextInput(document.getElementById('ta'));
}
"
-- in top.frames[0]
<script type="text/javascript">
function clearTextInput(txtInput) {
if (txtInput) {
txtInput.value = '';
}
}
</script>
This code guarantees that top.frames[2] is actually completely loaded before an
attempt is made to clear it's text area.