ranvel
ranvel

Reputation: 878

Use javascript AND PHP in one <input> tag?

I feel like I've looked around for the answer for this question, but most of the responses are very hacky: involving javascript that pops in via AJAX, redirects and other ways of modifying the DOM on the fly.

What I want to do is make the submit button disappear when a user submits a document (javascript) and submit the message via mail (php). The code I have is the following:

<form action="" method="post">
...
<input onclick="removeElements()" id="subButton" class="submit" name="submit" type="submit" value="submit">

The php mail function is in the same document.

Here is the removeElements() function:

var el = document.getElementById("subButton");
el.remove();
document.getElementById("thankYouMessage").setAttribute("style", "display:block");

The submit function works without the javascript call, but when I add the onclick="removeElements()" part, then the javascript part starts working, but the php is no longer executed.

I know that there are other methods for doing this, but in this case, I'm actually curious about why this doesn't function as I had planned. By removing the submit button, am I in effect killing the child PHP process mid(or pre)-execution?

Thanks!

Upvotes: 1

Views: 71

Answers (4)

YaBCK
YaBCK

Reputation: 3029

You could simple use the .hide functionality which JQuery gives you. It's very simple to use and very clean.

Example1 using JQuery:

$("#FormID").submit(function(e) 
{
   e.preventDefault();
   // Hide button
   $("#subButton").hide();
   // Display thank-you message
   $("#thankYouMessage").css("display", "block");
});

Example2 using JQuery:

$(document).ready(function() {
    $(".submit").click(function() {
       $("#subButton").hide();
       $("#thankYouMessage").css("display", "block");
       return false;
    });
});

Upvotes: 0

Gobea Alcoba Gonzalo
Gobea Alcoba Gonzalo

Reputation: 59

When you send the form reloads your page so I suggest:

  • Using Ajax and only delete button on the response, or
  • Not generate the button when reloads your page.

Jquery Ajax examples: You can see them here api.jquery.com/jquery.ajax/

Regards.

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31203

Don't remove the button, rather set visible: hidden or display: none for its style. This way it will still be in the document and will work, it just won't be shown.

Upvotes: 2

Gonzalo.-
Gonzalo.-

Reputation: 12682

If you add onclick you will have to fire the submit manually.

The other option is add your javascript call code in onsubmit="removeElements()" on the form tag. This way, it will execute your code after executing submit

Related question here

Upvotes: 2

Related Questions