add onclick function to a submit button

catchmikey picture catchmikey · Oct 18, 2012 · Viewed 522.2k times · Source

I'm just learning javascript and php. I created a contact form and I'd like the submit button to accomplish two things when I press it:

  1. submit the data to me (this part is working)
  2. read my onclick function (this part is not working)
<input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood()">

<?php
if ($_POST['submit']) {
 ////????? 
}
?>

I'm sending the data to my email, and so I get that. But the onclick function doesn't seem to work. I tried reviewing add onclick function for submit button but it didn't help.

Answer

manman picture manman · Oct 18, 2012

I need to see your submit button html tag for better help. I am not familiar with php and how it handles the postback, but I guess depending on what you want to do, you have three options:

  1. Getting the handling onclick button on the client-side: In this case you only need to call a javascript function.

function foo() {
   alert("Submit button clicked!");
   return true;
}
<input type="submit" value="submit" onclick="return foo();" />

  1. If you want to handle the click on the server-side, you should first make sure that the form tag method attribute is set to post:

    <form method="post">
    
  2. You can use onsubmit event from form itself to bind your function to it.

<form name="frm1" method="post" onsubmit="return greeting()">
    <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>