How to create a dialog with “Ok” and “Cancel” options

JavascriptDialog

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.');
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

How to do this using 'inline' JavaScript:

<form action="http://www.google.com/search">
  <input type="text" name="q" />
  <input type="submit" value="Go"
    onclick="return confirm('Are you sure you want to search Google?')"
  />
</form>

Solution 4 - Javascript

Avoid inline JavaScript - changing the behaviour would mean editing every instance of the code, and it isn’t pretty!

A much cleaner way is to use a data attribute on the element, such as data-confirm="Your message here". My code below supports the following actions, including dynamically-generated elements:

  • a and button clicks
  • form submits
  • option selects

jQuery:

$(document).on('click', ':not(form)[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('submit', 'form[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('input', 'select', function(e){
    var msg = $(this).children('option:selected').data('confirm');
    if(msg != undefined && !confirm(msg)){
        $(this)[0].selectedIndex = 0;
    }
});

HTML:

<!-- hyperlink example -->
<a href="http://www.example.com" data-confirm="Are you sure you want to load this URL?">Anchor</a>

<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>

<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
    <button type="submit">Submit</button>
</form>

<!-- select option example -->
<select>
    <option>Select an option:</option>
    <option data-confirm="Are you want to select this option?">Here</option>
</select>

http://jsfiddle.net/j88hju7h/5/">JSFiddle demo

Solution 5 - Javascript

You have to create a custom confirmBox. It is not possible to change the buttons in the dialog displayed by the confirm function.

jQuery confirmBox


See this example: https://jsfiddle.net/kevalbhatt18/6uauqLn6/

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>
function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // Do nothing
});

Pure JavaScript confirmBox


Example: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/127/

<div id="id_confrmdiv">confirmation
    <button id="id_truebtn">Yes</button>
    <button id="id_falsebtn">No</button>
</div>

<button onclick="doSomething()">submit</button>
Script
<script>
    function doSomething(){
        document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line

        document.getElementById('id_truebtn').onclick = function(){
           // Do your delete operation
            alert('true');
        };
        document.getElementById('id_falsebtn').onclick = function(){
             alert('false');
           return false;
        };
    }
</script>
CSS
body { font-family: sans-serif; }

#id_confrmdiv
{
    display: none;
    background-color: #eee;
    border-radius: 5px;
    border: 1px solid #aaa;
    position: fixed;
    width: 300px;
    left: 50%;
    margin-left: -150px;
    padding: 6px 8px 8px;
    box-sizing: border-box;
    text-align: center;
}

#id_confrmdiv button {
    background-color: #ccc;
    display: inline-block;
    border-radius: 3px;
    border: 1px solid #aaa;
    padding: 2px;
    text-align: center;
    width: 80px;
    cursor: pointer;
}

#id_confrmdiv .button:hover
{
    background-color: #ddd;
}

#confirmBox .message
{
    text-align: left;
    margin-bottom: 8px;
}

Solution 6 - Javascript

Or simply:

<a href="https://some-link.com/" onclick="return confirm('Are you sure you want to go to that link?');">click me!</a>

Solution 7 - Javascript

This plugin can help you jquery-confirm easy to use

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    confirm: function(){
        alert('Confirmed!');
    },
    cancel: function(){
        alert('Canceled!')
    }
});

Solution 8 - Javascript

You can intercept the onSubmit event using JavaScript.

Then call a confirmation alert and then grab the result.

Solution 9 - Javascript

This a full responsive solution using vanilla javascript :

// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");

function show_dialog() {
 /* A function to show the dialog window */
    overlayme.style.display = "block";
}

// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
 /* code executed if confirm is clicked */   
    overlayme.style.display = "none";
}

// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
 /* code executed if cancel is clicked */  
    overlayme.style.display = "none";
}

.popup {
  width: 80%;
  padding: 15px;
  left: 0;
  margin-left: 5%;
  border: 1px solid rgb(1,82,73);
  border-radius: 10px;
  color: rgb(1,82,73);
  background: white;
  position: absolute;
  top: 15%;
  box-shadow: 5px 5px 5px #000;
  z-index: 10001;
  font-weight: 700;
  text-align: center;
}

.overlay {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.85);
  z-index: 10000;
  display :none;
}

@media (min-width: 768px) {
  .popup {
    width: 66.66666666%;
    margin-left: 16.666666%;
  }
}
@media (min-width: 992px) {
  .popup {
    width: 80%;
    margin-left: 25%;
  }
}
@media (min-width: 1200px) {
  .popup {
    width: 33.33333%;
    margin-left: 33.33333%;
  }
}

.dialog-btn {
  background-color:#44B78B;
  color: white;
  font-weight: 700;
  border: 1px solid #44B78B;
  border-radius: 10px;
  height: 30px;
  width: 30%;
}
.dialog-btn:hover {
  background-color:#015249;
  cursor: pointer;
}

<div id="content_1" class="content_dialog">
    <p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
    <p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>

<button id="btn-show-dialog">Ok</button>


<div class="overlay" id="dialog-container">
  <div class="popup">
    <p>This will be saved. Continue ?</p>
    <div class="text-right">
      <button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
      <button class="dialog-btn btn-primary" id="confirm">Ok</button>
    </div>
  </div>
</div>

Solution 10 - Javascript

Another way to do this:

$("input[name='savedata']").click(function(e){
	   var r = confirm("Are you sure you want to save now?");
	   	 
	   //cancel clicked : stop button default action 
	   if (r === false) {
		   return false;
		}
		
		//action continues, saves in database, no need for more code
		
		
   });

Solution 11 - Javascript

xdialog provides a simple API xdialog.confirm(). Code snippet is following. More demos can be found here

document.getElementById('test').addEventListener('click', test);

function test() {
  xdialog.confirm('Are you sure?', function() {
    // do work here if ok/yes selected...
    console.info('Done!');
  }, {
    style: 'width:420px;font-size:0.8rem;',
    buttons: {
      ok: 'yes text',
      cancel: 'no text'
    },
    oncancel: function() {
      console.warn('Cancelled!');
    }
  });
}

<link href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>
<button id="test">test</button>

Solution 12 - Javascript

Made super simple, tiny vanilla js confirm dialog with Yes and No buttons.
It's a pity we can't customize the native one.

https://www.npmjs.com/package/yesno-dialog.

enter image description here

Solution 13 - Javascript

I'm currently working on a web workflow which already has it's own notifications/dialog boxes, and I recently (like, today) created a tiny, custom (and tailored to the project needs) YES/NO dialog box.

All dialog boxes appeard over a modal layer. Full user attention is required.

I define the options configurations in this way. This options are used to define the buttons text, and the values associated to each button when there clicked:

optionsConfig = [
   { text: 'Yes', value: true },
   { text: 'No', value: false }
]

The use of the function goes something like this:

const answer = await notifier.showDialog('choose an option', options.config);
if (answer) {
   // 'Yes' was clicked
} else {
   // 'No' was clicked!
}

What I do, it's simply creating a async event handler for each option, it means, there is a simple handler assigned to each button. Each handler returns the value of the option. The handlers are pushed inside an array. The array is then passed to Promise.race, and that is the return value of the showDialog method, which will correspond to the value's actual value (the one returned by the handler).

Can't provide too much code. As I said it's a very specific case, but the idea may be usefull for other implementations. Twenty lines of code or so.

Solution 14 - Javascript

Another solution apart from the others is to use the new dialog element. You need to make use of show or showModal methods based on interactivity with other elements. close method can be used for closing the open dialog box.

<dialog>
  <button class="yes">Yes</button>
  <button class="no">No</button>
</dialog>

const dialogEl = document.querySelector("dialog");
const openDialog = document.querySelector("button.open-dialog");
const yesBtn = document.querySelector(".yes");
const noBtn = document.querySelector(".no");
const result = document.querySelector(".result");

openDialog.addEventListener("click", () => {
  dialogEl.showModal();
});

yesBtn.addEventListener("click", () => {
  // Below line can be replaced by your DB query
  result.textContent = "This could have been your DB query";
  dialogEl.close();
});

noBtn.addEventListener("click", () => {
  result.textContent = "";
  dialogEl.close();
});

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');

body {
  font-family: "Roboto";
}

button {
  background: hsl(206deg 64% 51%);
  color: white;
  padding: 0.5em 1em;
  border: 0 none;
  cursor: pointer;
}

dialog {
  border: 0 none;
}

.result {
  margin-top: 1em;
}

<dialog>
  <button class="yes">Yes</button>
  <button class="no">No</button>
</dialog>
<button class="open-dialog">Click me</button>
<div class="result"></div>

Can I use?

Right now the compatibility is great with all the modern browsers.

Solution 15 - Javascript

The easiest way to ask before action on click is following

<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>

Solution 16 - Javascript

document.getElementById("button").addEventListener("click", function(e) {
   var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");
   if (cevap) {
     location.href='Http://www.evdenevenakliyat.net.tr';       
   }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncrchinView Question on Stackoverflow
Solution 1 - Javascripts4yView Answer on Stackoverflow
Solution 2 - JavascriptChuck NorrisView Answer on Stackoverflow
Solution 3 - JavascriptdanaView Answer on Stackoverflow
Solution 4 - Javascriptrybo111View Answer on Stackoverflow
Solution 5 - JavascriptKeval BhattView Answer on Stackoverflow
Solution 6 - JavascriptJavaRunnerView Answer on Stackoverflow
Solution 7 - Javascriptibrahim ozbolukView Answer on Stackoverflow
Solution 8 - Javascriptmarcelo-ferrazView Answer on Stackoverflow
Solution 9 - JavascriptAlouani YounesView Answer on Stackoverflow
Solution 10 - JavascriptArisView Answer on Stackoverflow
Solution 11 - Javascriptxia xiongjunView Answer on Stackoverflow
Solution 12 - JavascriptAlex SidorenkoView Answer on Stackoverflow
Solution 13 - JavascriptEmilio GrisolíaView Answer on Stackoverflow
Solution 14 - Javascriptm4n0View Answer on Stackoverflow
Solution 15 - JavascriptHassan QasimView Answer on Stackoverflow
Solution 16 - JavascriptalpcView Answer on Stackoverflow