Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add onclick function to a submit button

Tags:

submit

onclick

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.

like image 925
catchmikey Avatar asked Oct 17 '12 22:10

catchmikey


People also ask

Can you add onclick to submit button?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

What happens when submit button is clicked?

The form will be submitted to the server and the browser will redirect away to the current address of the browser and append as query string parameters the values of the input fields.


2 Answers

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>
like image 86
manman Avatar answered Sep 23 '22 04:09

manman


html:

<form method="post" name="form1" id="form1">         <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" /> </form> 

Javascript: to submit the form using javascript

function eatFood() { document.getElementById('form1').submit(); } 

to show onclick message

function eatFood() { alert('Form has been submitted'); } 
like image 34
stash_man Avatar answered Sep 23 '22 04:09

stash_man