Find It.

Situation: You have a perfectly good web page which contains a form. When the form is submitted, it submits twice when you expect it to only submit once. This can lead to lots of problems.

Assumption: The form is submitted by clicking an image input object (<input type="image">), which triggers a JavaScript function that in turn submits the form.

In short, you have something similar to this:



<title>My broke-ass webpage</title>

<script language="JavaScript">

	function someFunction()
          //... do some fun javascript






<form name ="myHtmlForm" action="" method="post" >

<input type="image" src="myImageFile.jpg" onclick="someFunction()">




Understand it.

Essentially the problem is the image input type. An under-documented feature of the image input is that it is actually a submit button. It behaves exactly the same as a submit input type. So, when the image is clicked, the form is submitted, period. However, in this case, the image also triggers a JavaScript function that also submits the form. So this is how your form is being submitted twice. Once for the image click, again for the JavaScript function.

Fix it.

There are plenty of ways to fix this problem. First, you could just not use image inputs. Secondly, (and this is my favorite option) you could not use JavaScript. However, knowing that neither of these options are likely to be obeyed, I'll explain a workaround for this problem.

Basically, you have to add "return false" to your onClick attribute. Yeah, I know. It's odd. But trust me. It works. Just go from using

<input type="image" src="myImageFile.jpg" onclick="someFunction()"> 

and instead, use

<input type="image" src="myImageFile.jpg" onclick="someFunction(); return false">

It disables the default behavior for the image input type. I don't quite understand why it works, but it does.

Hopefully this will help someone.

lj says: you could also just use an <IMG> instead of <INPUT type = "image">, as onclick is a valid attribute for <IMG> (as well as, i think, any block tag.)

Reply: This is true, although not all browsers support onClick attributes for plain images.

Log in or register to write something here or to contact authors.