简体   繁体   中英

Confirm before a form submit

I have searched for an answer but couldn't find one!

I have a simple form,

<form action="adminprocess.php" method="POST">
    <input type="submit" name="completeYes" value="Complete Transaction" />
</form>

How would I adjust this to confirm before processing the form?

I tried onclick, but couldn't get it working.

Any ideas?

UPDATE - What I now have.

<script type="text/javascript">
var el = document.getElementById('myCoolForm');

el.addEventListener('submit', function(){
return confirm('Are you sure you want to submit this form?');
}, false);
</script>

<form action="adminprocess.php" method="POST" id="myCoolForm">
     <input type="submit" name="completeYes" value="Complete Transaction" />
</form>

HTML:

<form action="adminprocess.php" method="POST" id="myCoolForm">
    <input type="submit" name="completeYes" value="Complete Transaction" />
</form>

JavaScript:

var el = document.getElementById('myCoolForm');

el.addEventListener('submit', function(){
    return confirm('Are you sure you want to submit this form?');
}, false);

Edit: you can always use inline JS code like this:

<form action="adminprocess.php" method="POST" onsubmit="return confirm('Are you sure you want to submit this form?');">
    <input type="submit" name="completeYes" value="Complete Transaction" />
</form>
<input type="submit" onclick="return confirm('Are you sure you want to do that?');">

The correct event is onSubmit() and it should be attached to the form. Although I think it's possible to use onClick, but onSubmit is the correct one.

If you're already using jQuery.. you can use an event handler to trigger before submission

$(document).ready(function() {
   $("#formID").submit(function(){
      // handle submission
   });
});

Reference: http://api.jquery.com/submit/

 var submit = document.querySelector("input[type=submit]"); /* set onclick on submit input */ submit.setAttribute("onclick", "return test()"); //submit.addEventListener("click", test); function test() { if (confirm('Are you sure you want to submit this form?')) { return true; } else { return false; } } 
 <form action="admin.php" method="POST"> <input type="submit" value="Submit" /> </form> 

如果你有多个提交按钮来执行不同的操作,你可以这样做。

<input TYPE=SUBMIT NAME="submitDelete"  VALUE="Delete Script" onclick='return window.confirm("Are you sure you want to delete this?");'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM