Jump to content

stopping form submit with plain JavaScript


phppup

Recommended Posts

I have my PHP spitting out an HTML table that includes a button for editing at the end of each row

echo "<td><form action='' method='POST' <button type='submit' name='startEdit' value=".$row['id']." onclick='myFunction();'>Edit</button></form></td>";

I want a confirmation to pop up before advancement to the editing form page

function myFunction() {
  
  if(!confirm('Do you really want to do this?')) {
    return false;
  }
  
}

Obviously, if TRUE is the result, I want the page to advance, and for FALSE, I want the page to remain.

I have not been able to achieve the desired result either by changing the ACTION to action="xyz.php" OR with JS  window.location.href = 'http://www.w3schools.com';

Please tell me what I am missing?

Link to comment
Share on other sites

Well, first thing you're missing is valid HTML. Second is that you're using inline Javascript events from the '90s instead of modern event handlers. And third is that if you want to know about the form submitting then you should be having the form tell you when it's about to be submitted instead of the button when it's being "clicked".

Fourth is that either of these is better than a confirm() dialog:
1. A checkbox in the form that says they want to do whatever it is the form does. Mark it required so the form won't submit without it being checked. Then you don't have to write any code at all.
2. A modal popup where you can customize everything and make it fit with the appearance of your site. The form's button instead triggers the modal, and the modal is what actually submits the form.

Fifth is that cancelling an event requires either returning false from the inline code (which is also '90s code) or using an Event object that you can .preventDefault() on (modern).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.