On my Struts2 application, I have some buttons that will delete items from a table. So far, so good. Now, I'm trying to use jQuery to present the users with an alert to confirm if they really want to delete the chosen item. To do this, what I have in mind is what I think it is the most obvious approach:
- User clicks on the "delete" button;
- Show alert to the user (it contains two links: one to cancel the delete action and another one to confirm it);
2.1. If the user presses "cancel", the alert simply goes away;
2.2. If the user presses "confirm", the item is deleted, and then the alert goes away;
What I've got so far:
JSP:
<table>
<tr>
[...]
<td><a href="<s:url action="deleteexperiment"><s:param name="id"><s:property value="exp_id"/></s:param></s:url>" class="delete ink-button all-100">delete</a></td>
[...]
</tr>
</table>
<div id="confirm-delete" class="ink-alert basic" role="alert" style="display: none">
<p class="quarter-bottom-padding"><b>Confirm delete:</b> Do you really want to delete this experiment?</p>
<button id="no" class="ink-button all-20 red">Cancel</button>
<button id="yes" class="ink-button all-20 green">Confirm</button>
</div>
<script type="text/javascript">
$(document).ready(function()
{
$('.delete').click(function(e)
{
e.preventDefault();
$('#confirm-delete').show();
$('#yes').click(function(event)
{
// resume e.preventDefault(), i.e., continue redirecting to the original href on the table above
$('#confirm-delete').hide();
});
$('#no').click(function(event)
{
$('#confirm-delete').hide();
});
});
});
</script>
I've tried like 20 different approaches (in what concerns trying to restore the original behaviour to the link - the commented line) with no luck. Please note that the href
atrribute contains Struts tags, so something like window.location.href = "<s:url action="deleteexperiment"><s:param name="id"><s:property value="exp_id"/></s:param></s:url>";
won't work, because jQuery won't "know" what is the ID, I guess (it will redirect to http://localhost:8080/AppName/deleteexperiment.action?id=
, so the ID is empty). Unless it would be possible to pass the ID to jQuery when calling the click()
function, of course. Is that possible? Which other options are left for me? Thanks.
This should work:
$(document).ready(function()
{
$('.delete').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href'); // store the href attr
$('#confirm-delete').show();
$('#yes').click(function(event)
{
// resume e.preventDefault(), i.e., continue redirecting to the original href on the table above
window.location.href = href; // redirect with stored href
$('#confirm-delete').hide();
});
$('#no').click(function(event)
{
$('#confirm-delete').hide();
});
});
});