I'm trying to implement some very basic (in my opinion) functionality with jQuery. I have Delete
link:
<a href="/Delete" class="prompt-for-delete">Delete</a>
and all I want is when the link is clicked to show some kind of confirmation window like:
Are you sure you want to delete this : Yes/No
And if No
is clicked I want to prevent the link from executing. I use jquery-1.10.2.min.js
and
jquery-ui-1.10.3.min.js
my HTML is:
<div id="dialog-confirm" ></div>
<a href="/Delete" class="prompt-for-delete">Delete</a>
I tried several options I found on the internet. The last one is:
$(document).ready(function () {
$('.prompt-for-delete').click(function (e) {
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete all items": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
});
which is just to get something working but with this I get the dialog opened and automatically closed after a second. It seems like something very standard so could you provide an example of how to achieve this?
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.
We can use the event. defaultPrevented property in the event object. It returns a boolean indicating if the event. preventDefault() was called in a particular element.
You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.
Confirm()
is what you are looking for. This is how you use it:
var answer=confirm('Do you want to delete?');
Your HTML would be like:
<a id="delete" href="/Delete" class="prompt-for-delete">Delete</a>
And your javascript:
$('#delete').on('click',function(e){
e.preventDefault();
var answer=confirm('Do you want to delete?');
if(answer){
alert('Deleted');
}
else{
alert('Not Deleted');
}
});
You can see the demo here: http://jsfiddle.net/c9cLW/1/
Edit:
Here is updated redirection and preventing event:
Script:
$('#delete').on('click',function(e){
var answer=confirm('Do you want to delete?');
if(answer){
alert('Deleted');
}
else{
e.preventDefault();
}
});
Updated Fiddle: http://jsfiddle.net/c9cLW/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With