Displaying a confirmation dialog to the user before submitting a form on a web page is part of a good UX. Especially for important actions, such as deleting or modifying data, asking for confirmation helps prevent mistakes. In this article, we’ll introduce how to implement this feature.
Basic Style Settings
First, adjust the design of the confirmation button (.btn1
). Below is a sample CSS. You can modify it to fit your site’s design.
<style>
* {
padding: 0;
margin: 0;
}
body {
font-size: 18px;
text-align: center;
}
h1{
text-align: center;
font-size: 24px;
padding: 20px 0 40px 0;
line-height: 1.8em;
}
.btn1{
padding: 6px;
}
</style>
HTML Implementation
Below is a sample form that displays a confirmation dialog before submission. Assign class="dadform"
to the form tag. This form includes a “Confirm” button (type="submit"
).
<h1>Use window.confirm and jQuery’s submit to display a confirmation dialog before form submission.<br>Click the “Confirm” button below.</h1>
<form action="https://dad-union.com" method="GET" class="delform">
<input class="btn1" name="btn" type="submit" value="Confirm">
</form>
Implementing the Confirmation Dialog with window.confirm and jQuery submit
In this section, we’ll implement the process to display the dialog. Since we’re using jQuery, make sure to include the jquery-3.1.1.min.js
file.
This script displays a confirmation dialog when the confirm button is clicked using window.confirm
. If the user clicks “OK,” they’ll be redirected to the specified URL. If they click “Cancel,” nothing happens.
By writing $("form-class").submit(function(){})
, you can trigger a process when submitting the form. In this case, when the confirm button (type="submit"
) inside the form (class="dadform"
) is clicked, a confirmation dialog will appear before submission using window.confirm()
. Clicking “OK” redirects to https://dad-union.com
, while clicking “Cancel” does nothing.
<script type="application/javascript" src="jquery-3.1.1.min.js"></script>
<script type="application/javascript">
$(".delform").submit(function(){
if(window.confirm('Is it okay to move to dad-union.com?')) {
return true;
} else {
return false;
}
});
</script>
Demo Page: Displaying a Confirmation Dialog Before Form Submission Using window.confirm and jQuery submit
If you’d like to see this implementation in action, you can check the demo page via the link below.
Summary
Using window.confirm
and jQuery submit
to display a confirmation dialog is very useful for preventing user errors or confirming actions before executing them. It’s especially effective when users delete important data or navigate to another page, allowing them to confirm their intent. Implementing this on your site can enhance the overall user experience.
*Please use this code at your own risk.
Do not copy the Google Analytics tag in the demo page’s head section.