Created
April 21, 2024 20:39
-
-
Save douglasmiranda/85452cbb830545cccc23ce962215dfb9 to your computer and use it in GitHub Desktop.
[HTML / Javascript form] multiple submit buttons/actions | capturing submit action server side | alert before submit javascript may affect submit button on server side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Lets say you have a form, with multiple submit buttons: | |
<form method="POST"> | |
<button type="submit" name="save"> | |
save | |
</button> | |
<button type="submit" name="send-all"> | |
send all | |
</button> | |
</form> | |
You wanna ask if the user is sure about the button they clicked on. | |
This works, it will prevent the submit and only submit the form if you confirm first. | |
But this will not send the button "send-all" as POST data, so if you plan to use in backend | |
to differentiate action "save" from "send-all" you may have problems. | |
<script> | |
var send_all_button = document.getElementById("send-all"); | |
send_all_button.addEventListener("click", function (event) { | |
event.preventDefault(); | |
if ( confirm("Are you sure you wish to send all?") === false ) { | |
return false; | |
} else { | |
this.form.submit(); | |
} | |
}); | |
</script> | |
Solution: | |
Just use preventDefault() when user answer 'no'. Otherwise continue your action originate from 'send-all' button. | |
<script> | |
var send_all_button = document.getElementById("send-all"); | |
send_all_button.addEventListener("click", function (event) { | |
if ( confirm("Are you sure you wish to send all?") === false ) { | |
event.preventDefault(); | |
return false; | |
} else { | |
return true; | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment