Click to See Complete Forum and Search --> : problem with form elements


Giorgos
03-15-2003, 12:54 PM
Greetings,

i'm going nuts can someone explain me why this doesn't work:

<html>

<head>
<script type="text/javascript">

function foo(f)
{
for (var i = f.firstChild; i ; i = i.nextSibling)
{
if (i) alert("exists");
document.writeln(i.name);
}

</script>
</head>

<body>
<form>
<input type=checkbox name="a">
<input type=checkbox name="b">
<input type=checkbox name="c">
<input type=checkbox name="d">
<input type=button value="Press me" onclick="foo(this.form)">
</form>

</body>
</html>

Instead of getting an alert message and a printed meesage for all form elements i'm only getting for the first and it seems like all elements are undefined except the first. What's happening?

Thanks in advance

khalidali63
03-15-2003, 01:04 PM
That is because when document.writeln is executed,it wipes of everything below that line from the memory,or rest of the code is out of scope.

A way around this if you have to use document.write is

var str="";

function foo(f)
{
for (var i = f.firstChild; i ; i = i.nextSibling)
{
if (i) alert("exists");
str+=i.name+"<br>";
}

document.writeln(str);

Hope this helps

Cheers

Khalid