How do I popup an alert box for verification when the user clicks a link on the page? [closed]

StackOverflow https://stackoverflow.com/questions/17537718

Frage

I am building a small CMS and I have a delete option for post, pages etc. It is a link but now I need to make it show a popup alert or something when clicking on it just to verify if people really do want to delete the article. If the user clicks "yes" then it with continue to that link and delete, but if people click "NO" then it won't let the browser to go to that link and delete the article.

I know I can do this with jQuery somehow but I am 2 days without sleeping and I can't think straight. Any ideas?

War es hilfreich?

Lösung

You can use jQuery to send up a confirm dialog. If the user clicks OK and confirms then you can return true which will allow the link to be followed automatically. If the user clicks cancel you will cancel the event's default (the default for a click event on a link is to go to it) and then the link will not be followed.

HTML:

<a class="confirm" href="http://www.microsoft.com">Link</a>

JavaScript (with jQuery):

$(".confirm").on("click", function(event){
    if(confirm("Are you SURE....?")){
       return true;
    } else {
        event.preventDefault();
        return false;
    }
});

Try it out on jsFiddle!

Andere Tipps

$('a.confirm').click(function() {
    return confirm('Really delete this?');
});

HTML:

<a href='url_to_delete_page' onclick='return check()'>Click</a>

JavaScript:

<script type="text/javascript">
function check(){
        return confirm("Really delete it?");
}
</script>

If you make a confirm dialog, you can copy the href from the pressed link.

The way this code works, is it automatically binds to links with the class confirm. It then modifies a confirm dialog to have the yes button do the original link's action, and no to hide the dialog.

demo

The HTML:

<div class="dialog" id="confirmation">
  <div class="title">Are you sure?</div>
  <a href="#" class="yes">Yes</a>
  <a href="#" class="no">No</a>
</div>

<a href="#delete" class="delete confirm">Delete</a>

And the JavaScript.

$('#confirmation.dialog .no')
  .click(function(){
    $('#confirmation.dialog').hide();
});

$('a.confirm').on('click', function(){
  var $el = $(this), link = $el.attr('href'),
      $confirm = $('#confirmation.dialog'),
      $yes, $no;

  $confirm.show();
  $yes = $confirm.find('.yes');

  $yes.attr('href', link);

  return false;
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top