I am going to make a button to take an action and save the data into a database.
Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.
How do I display such a dialog?
You can create a JavaScript confirmation box that offers yes and no options by using the confirm() method. The confirm() method will display a dialog box with a custom message that you can specify as its argument.
The confirm() method displays a dialog box with a message, an OK button, and a Cancel button. The confirm() method returns true if the user clicked "OK", otherwise false .
A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
window. confirm() instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels the dialog.
You’re probably looking for confirm()
, which displays a prompt and returns true
or false
based on what the user decided:
if (confirm('Are you sure you want to save this thing into the database?')) { // Save it! console.log('Thing was saved to the database.'); } else { // Do nothing! console.log('Thing was not saved to the database.'); }
var answer = window.confirm("Save data?"); if (answer) { //some code } else { //some code }
Use window.confirm
instead of alert. This is the easiest way to achieve that functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With