views:

65

answers:

1

I was creating a form validator for a client and ran into this weird error ONLY in Internet Exploder (Explorer) 7/8....

'return' outside of function, line 1, char 1

Of course, there was no code whasoever on line 1, it was a simple commented statement. And there was nothing wring with it in any way. So I knew it was just a debug miss-direct.

I have been pulling my hair out to understand what could be wrong here...

I have already ruled out the obvious: return statements in a loop, too many return statements in a single function, any returns actually outside of a legitimate function definition.

Has anybody else had any instances when this has happened to you?

+4  A: 

I got it!

The problem was that I was using a return statement to override the default behavior for my form and it was assigned to a property, BUT it was not placed inside an anonymous function!

I had a form element that was set up like this:

<form name="formname" onSubmit="javascript:validateForm(this);" action="javascript:return false;" method="post" enctype="multipart/form-data">

All I needed to change was the action property to this:

… action="javascript:function(){return false};"

It now works flawlessly!

Hope this saves someone else from the hell I went through.

exoboy
Another way of achieving this is by returning `false` `onsubmit`. Please let the `action` attribute point to a valid page on your server, so you have a fallback option when JavaScript is turned off/blocked.
Marcel Korpel
`javascript:` URLs are evil; never use them, especially for `action`. If there is really nowhere useful to point the form for non-JS users, you can give it a useless action like `#`, and use `onsubmit="return false"` to stop it submitting (no `javascript:` prefix is needed on event handlers, which are not URLs; including it does nothing sensible). Or, if you don't need to associate script-only form fields with anywhere to submit them, you can just omit the form tag.
bobince
Sorry, but in some browsers the hash "#" generates an extra HTTP request, which should be avoided. Especially since Google is panicking over page load speed. This info is to let people know that using return ANYWHERE outside of a function will cause IE to throw an error. Any time you use "return", no matter which property it is in, it needs to be enclosed in a function: anonymous or otherwise.By returning false you prevent the browser from performing its default behavior. It works in ALL browsers. Including the "javascript:" portion is simply good practices: It ensures proper code type'ing.
exoboy