Struts2 / jQuery: resume href redirect after e.preventDefault ();
In my Struts2 application, I have several buttons that will remove items from the table. So far, so good. Now I'm trying to use jQuery to present users with a warning to confirm if they really want to remove the selected item. For this I mean that I believe this is the most obvious approach:
- The user clicks the "Delete" button;
- Show a warning to the user (it contains two links: one to cancel the delete action, and the other to confirm);
2.1. If the user clicks cancel, the warning just disappears;
2.2. If the user clicks confirm, the item is removed and then the warning disappears;
What I have 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 (as far as trying to restore the original link behavior - commented line) with no luck. Note that the attribute href
contains Struts tags, so something window.location.href = "<s:url action="deleteexperiment"><s:param name="id"><s:property value="exp_id"/></s:param></s:url>";
doesn't seem to work because jQuery won't "know" what the ID is, I guess (it will redirect to http://localhost:8080/AppName/deleteexperiment.action?id=
, so the ID is empty). If it wasn't for the ability to pass the jQuery id when calling the function click()
, of course. Is it possible? What other options are left for me? Thank.
source to share
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();
});
});
});
source to share