Click to See Complete Forum and Search --> : Yet another one: How do I handle JS errors in my script?


karayan
07-23-2003, 11:09 AM
I have a while loop that needs to run until an object cannot be found. That is to say, as soon as JS tries to access an object in document that cannot be found, I want to stop the loop and continue the script, but not cause an error message. Can try...catch be used for that kind of thing?

Thanks.

George

AdamBrill
07-23-2003, 11:26 AM
You could do something like this:<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function run(){
x=1;
while(eval("document.form1.test"+x)){
alert(eval("document.form1.test"+x+".value"));
x++;
}
}
</script>
</head>

<body>

<form name=form1 action="wherever.php" method="post">
<input type=text name=test1>
<input type=text name=test2>
<input type=text name=test3>
<input type=text name=test4>
<input type=text name=test5>
<input type=text name=test6>
</form>
<a href="#" onclick="run(); return false;">run</a>
</body>
</html>

karayan
07-23-2003, 11:54 AM
Adam:

Are you saying that if the object in parentheses does not exist, then

eval("document.form1.test"+x)

will return false?

George

Charles
07-23-2003, 12:15 PM
If an object cannot be found then its value is taken to be "undefined" and "undefined" is taken to be false in the boolean context. All you need is something like if (window.foo) {window.foo()} else {window.fie()} or var fum = window.foo ? window.foo() : window.fie();

It is extremely rare to need to use "exec()".

AdamBrill
07-23-2003, 12:27 PM
Ok, I know it can be done without eval(), but is there a reason not to use it? Is there a compatability issue there?

Anyway, you can do the same thing without eval(). Change the function to this:function run(){
x=1;
while(document.form1['test'+x]){
alert(document.form1['test'+x].value);
x++;
}
}