JavaScript return false not stopping form submission
We've got some code like this that has been working for some time. It's for a button that submits an html form, unless a nearby textbox is empty. I've taken this snippet directly from our code; I've changed the contents of the fields, but haven't deleted anything.
<input
type="image"
name="inputName"
id="inputId"
src="someImage"
alt="altText"
onclick="
javascript:var obj = document.all ? document.all["aTextInputFormFieldId"] :
document.getElementById("aTextInputFormFieldId");
if(obj.value.length == 0)
{
alert('It is 0!');
return false;
};"
style="someStyle" />
(The original code is all on one line, but linebreaks have been added here for clarity).
It seems to work perfectly in Firefox. But in IE, it fails in a way that I can't understand: if the input field (aTex开发者_如何转开发tInputFormFieldId) is empty, it puts up the alert, but then submits the form anyway after the user clicks the okay button on the alert.
When I did a view source on the entire page, and copied it locally, it seems to work perfectly; it either submits the form, or puts up the alert, and then refuses to submit.
My best current (but still lousy) theory is that one of the included JavaScript libraries is doing something funny, which would explain why it failed on the real site, but fails when I copy it locally (since I didn't grab the various libraries it's importing.) This makes logical sense, and I'll check it out by grabbing the libraries too, but I'm having a hard time imagining what these libraries could be doing to mess this up (or why)...they're just normal utility libraries like jquery, utility functions, etc.
So does anyone have a theory about what could be happening here?
You mentioned jQuery, jQuery can interfere with your form if it is doing anything through its submit()
handler. Check to see if jQuery.submit()
is bound to your form.
Usually when doing pure javascript it is not enough to return false. Depending on what you want to accomplish you might want to look at preventDefault
or stopPropagation
When working with Internet Explorer be aware that the event object is not passed to the function but can be found in window.event
instead.
Update
Internet explorer might want you to use event.returnValue = false;
instead. In your case that would be window.event.returnValue = false;
when targeting IE.
Good luck
Javascript protocol links have to be one line, ie. no new lines.
onclick="javascript:var obj = document.all ? document.all["aTextInputFormFieldId"] :document.getElementById("aTextInputFormFieldId"); if(obj.value.length == 0){alert('It is 0!'); return false;};"
精彩评论