ChatGPT解决这个技术问题 Extra ChatGPT

How to display a confirmation dialog when clicking an <a> link?

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?


k
kapa

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>

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?
@Tophe The confirm dialog itself has nothing do with specific elements.
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?
@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.
@Ulysnep According to your edit suggestion there was a bug when omitting the semicolon after confirm(…) in the inline handler. I could not reproduce that.
W
Wolfack

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>

Ans given by @kapa is very easy and less messy
great job.i want to call another js method which is call on the success of conformation. This is solve my problem.
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.
C
Community

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:

addEventListener().

Conditional ('ternary') operator.

confirm().

getElementsByTagName().

onclick.

if () {}.


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?
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.
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.
@bažmegakapa: I...tend to agree; but I must confess I've yet to become comfortable with the addEventListener() model.
You can replace if(check == true) with if(check).
C
Community
<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>

e
erik

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


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...
Two libraries for this simple thing?
C
Chad Killingsworth

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);

If you are caring about old IEs, don't forget window.event.
F
Florian Margaine

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.


S
Salvioner

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'); }); }); Launch nuke!

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


S
Shah Abd Hafiz

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.