Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript alert box unnecessarily submits form

I have a simple javascript method to show an alert box. The method is called when a button is clicked (which is between the form tags). The alert is supposed to simply display a help dialog, but when the user presses the "ok" button on the alert box it submits the form! I cannot figure out how to prevent this. I've tried changing how I make the button and my alert method, but nothing seems to make a difference. Here is my code:

<script type="text/javascript">
function help(){      
    alert("Displaying help...");
}
</script>

Below is how I've created the button. I also tried creating the button with button tags, but the same problem occurred.

<form action="./go.php" method="post">
<input type="image" src="./help.png" name="help" width="25" height="25" onclick="help()">
.
.
.
</form>

Any help on how I can prevent the alert box from submitting the form is greatly appreciated. Thanks in Advance!

like image 912
ORL Avatar asked Jan 23 '26 23:01

ORL


2 Answers

The best way to fix this would be to use a regular <img> tag

<img src="./help.png" name="help" width="25" height="25" onclick="help()" />

But returning false from your code would probably work too

function help(){      
    alert("Displaying help...");
    return false;
}
like image 61
Adam Rackis Avatar answered Jan 25 '26 13:01

Adam Rackis


Add a return false; in your function:

<script type="text/javascript">
function help(){      
    alert("Displaying help...");
    return false;
}
</script>
like image 42
Virendra Avatar answered Jan 25 '26 13:01

Virendra