JavaScript alert box with confirm on button press
I have this link:
<p id="accept-favor"><a title="Accept this Favor" href="?wp_accept_favor=<?php comment_ID(); ?>">Accept this Favor</a></p>
I want to show a JavaScript alert box when a user clicks it saying: "Are you sure you would like to accept this reply a开发者_运维问答s your favor?" with two buttons one saying "Yes" which will allow the function to run and the other saying "No" which will just cancel the postback and keep the user on the page.
How would I do this? Thanks :)
You can easily do it with a confirm onclick:
<p id="accept-favor"><a title="Accept this Favor"
href="?wp_accept_favor=<?php comment_ID(); ?>"
onclick="return confirm('Are you sure you would like to accept this reply as your favor?');"
>Accept this Favor</a></p>
Though this will say OK/Cancel instead of Yes/No. If you really want Yes/No, you'll have to use a custom dialog.
You can write onclick="return confirm('Are you sure?');"
.
The confirm
function shows an OK / Cancel dialog and returns true
if the user clicked OK.
return
ing false
from an onclick
handler will cancel the default action of the click.
You can use this function:
myFunction() {
var x;
if (confirm("Are you sure?") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
return x;
}
myFunction();
As other answers talk about direct onclick, I would like to present a solution for a "nicer" (IMO=in my opinion) version using the addEventListener
and preventDefault
methods. Because this way you could bind more click handlers.
HTML
<a href="#" id="confirmClickActionElementId">click me</a>
JavaScript
document
.getElementById("confirmClickActionElementId")
.addEventListener("click", function( e ){ //e => event
if( ! confirm("Do you really want to do this?") ){
e.preventDefault(); // ! => don't want to do this
} else {
//want to do this! => maybe do something about it?
alert('Ok, lets do this!');
}
});
Fiddle: http://jsfiddle.net/ouyf86ya/
...or the old "return
" way:
document
.getElementById("confirmClickActionElementId")
.addEventListener("click", function( ){
return confirm("Do you really want to do this?") ;
});
Fiddle: http://jsfiddle.net/y2jLpkbb/
精彩评论