344

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.

<a href="delete.php?id=22">Link</a>

If the user clicks “Yes”, the link should load, if “No” nothing will happen.

I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Christoffer
  • 7,470
  • 9
  • 39
  • 55

9 Answers9

750

Inline event handler

In the most simple way, you can use the confirm() function in an inline onclick handler.

<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>

Advanced event handling

But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<script type="text/javascript">
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    };
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);
    }
</script>

This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.

jQuery

I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:

<a href="delete.php?id=22" class="confirmation">Link</a>
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
    $('.confirmation').on('click', function () {
        return confirm('Are you sure?');
    });
</script>
kapa
  • 77,694
  • 21
  • 158
  • 175
  • Was it really that easy! Am I embarrassed or what! I just assumed that only worked on forms. Does the confirm dialog work for every clickable element? – Christoffer May 05 '12 at 14:42
  • 1
    @Tophe The confirm dialog itself has nothing do with specific elements. – kapa May 05 '12 at 14:46
  • 1
    For something as simple as this, is it really necessary to separate the HTML and JavaScript? What issues would you foresee by leaving such a simple and short function inline? – Ciaran Gallagher Feb 11 '13 at 00:55
  • 5
    @CiaranG It always starts like this :), then you add this and that, etc. If you manage to embrace separation of concerns, you will feel cleaner if you get rid of most of these inline handlers. They just have nothing to do in your HTML. At least in my opinion, and at least in most cases. There are always special circumstances - laziness should not be one of them. – kapa Feb 11 '13 at 07:34
  • @Ulysnep According to your [edit suggestion](http://stackoverflow.com/review/suggested-edits/9154255) there was a bug when omitting the semicolon after `confirm(…)` in the inline handler. I could not reproduce that. – Sebastian Simon Aug 13 '15 at 19:36
  • First example does not work since I click cancel in dialog box it still goes to the link. @Wolfack answer works well in this case! – Gediminas Šukys May 02 '18 at 09:39
  • Searation of Javascript and HTML is not always desirable. In your advanced misleading event handling one can not tell from the HTML if the link is followed or not (since the JS is separated). It can also confuse bots who often just parse the HTML as is, without additional http requests. Also today, 10 years after your answer, the jQuery note is not true anymore. – Jan Turoň Jan 25 '22 at 17:54
38

You can also try this:

<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
    Link Text
</a>
Wolfack
  • 2,667
  • 1
  • 26
  • 50
  • Ans given by @kapa is very easy and less messy – dipenparmar12 Jan 12 '20 at 08:03
  • great job.i want to call another js method which is call on the success of conformation. This is solve my problem. – Ehsan ul haq Sep 03 '20 at 13:12
  • 1
    Very ugly idea to just mix return false, preventDefault() and stopPropagation() and whatever other methods related to suppressing anything. In links, propagation of clicks does not have any meaning. If one does not want to rely on return false (as some reported it is not working sometimes), `onclick="confirm('really?') || event.preventDefault()"` does the same as your code without the irrelevant clutter. – Jan Turoň Jan 25 '22 at 18:00
  • Can be simplified with `onclick="return confirm('Delete selected item?');"` – Latheesan Jun 28 '23 at 03:21
19

I'd suggest avoiding in-line JavaScript:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        var check = confirm("Are you sure you want to leave?");
        if (check == true) {
            return true;
        }
        else {
            return false;
        }
    };
}​

JS Fiddle demo.

The above updated to reduce space, though maintaining clarity/function:

var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].onclick = function() {
        return confirm("Are you sure you want to leave?");
    };
}

JS Fiddle demo.

A somewhat belated update, to use addEventListener() (as suggested, by bažmegakapa, in the comments below):

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');

for (var i = 0, len = aElems.length; i < len; i++) {
    aElems[i].addEventListener('click', reallySure);
}

JS Fiddle demo.

The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:

function reallySure (event) {
    var message = 'Are you sure about that?';
    action = confirm(message) ? true : event.preventDefault();
}

function actionToFunction (event) {
    switch (event.target.tagName.toLowerCase()) {
        case 'a' :
            reallySure(event);
            break;
        default:
            break;
    }
}

document.body.addEventListener('click', actionToFunction);

JS Fiddle demo.

Because the event-handling is attached to the body element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName of a, the click-handling is passed to the reallySure() function.

References:

Community
  • 1
  • 1
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Thank you. The short inline confirm solution worked. Why do you suggest avoiding inline code? I usually keep away from inline CSS for obvious reasons, but what the reasons in short javascript snippets? – Christoffer May 05 '12 at 14:47
  • For exactly the same reason that in-line CSS is inadvisable, it's harder to maintain, and it leads to messier HTML and requires an inordinate amount of work to update if the requirements change. – David Thomas May 05 '12 at 14:49
  • I agree with the point of not using inline handlers. But if we attach our handlers in the script anyways, the advanced model should be used (`addEventListener`). +1 though. – kapa May 05 '12 at 14:51
  • @bažmegakapa: I...tend to agree; but I must confess I've yet to become comfortable with the `addEventListener()` model. – David Thomas May 05 '12 at 14:54
  • You can replace `if(check == true)` with `if(check)`. – Anonymous Apr 01 '20 at 21:05
  • please just `return confirm("Are you sure you want to leave?");` and save 6 lines. – Florian F Jun 15 '23 at 12:35
17
<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>
Community
  • 1
  • 1
coder
  • 13,002
  • 31
  • 112
  • 214
1

jAplus

You can do it, without writing JavaScript code

<head>
   <script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
   <script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
   <a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>

Demo page

erik
  • 63
  • 1
  • 12
    Thanks for sharing, but of course you are using Javascript, you are adding an entire library to handle something very simple. Is it worth it? I don`t know that library, I will read about it, if you use it for other purposes as well, maybe it is worth the extra load... – Marcos Buarque Dec 24 '14 at 21:29
  • 1
    Two libraries for this simple thing? – maracuja-juice Jul 17 '17 at 18:37
1

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

0

This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).

function myClickHandler(evt) {
  var allowLink = confirm('Continue with link?');
  if (!allowLink) {
    evt.returnValue = false; //for older Internet Explorer
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
}

You can attach this handler with either:

document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);

Or for older versions of internet explorer:

document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);
Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57
0

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0

Most browsers don't display the custom message passed to confirm().

With this method, you can show a popup with a custom message if your user changed the value of any <input> field.

You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:

$(document).ready(function() {
  let unsaved = false;
  // detect changes in all input fields and set the 'unsaved' flag
  $(":input").change(() => unsaved = true);
  // trigger popup on click
  $('.dangerous-link').click(function() {
    if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {
      return; // user didn't confirm
    }
    // either there are no unsaved changes or the user confirmed
    window.location.href = $(this).data('destination');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="text" placeholder="Nuclear code here" />
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">
    Launch nuke!
</a>

Try changing the input value in the example to get a preview of how it works.

Salvioner
  • 303
  • 5
  • 16