We have a js function that redirects the user to a new page from a dropdown using Struts2. Here is the code.
The Struts2 dropdown that starts everything:
<s:select name="selectName" list="List" listKey="nameCode" headerKey='-1'
listValue="description" headerValue="Please select..." value="namedValue" onchange="redirectNextPage(this.value)" />
Here is the redirect function that fires next:
function redirectNextPage(id){
var page = "<s:url action='<path>.action'/>?<param>=";
window.location.href=(page + id);
}
I need to use a selector to capture window.location.href and bind it to my UnBindWindow function.
//Bind Links we dont want to affect
$('a[href^="http://"]').bind('focus', UnBindWindow); //Code not working?
//UnBind Function
function UnBindWindow(){
$(window).unbind('beforeunload', ReturnMessage);
}
...
I incorrectly assumed that focus would be the proper DOM event type I needed. What happens is the select goes to the javascript function and then the onbeforeunload event fires without my jQuery code getting called.
How do I properly bind an event to the window.location.href so I can prevent a beforeunload dialog from firing off the select dropdown, but still work for other elements on the jsp page?
After debugging I realized that the Struts2 tag was capturing the event and it wasn't bubbling for jQuery to intercept.
I never could hit this code:
$('select').change(function() {
alert('This worked!');
});
However, knowing the problem now, I put the unbind directly into the redirectNextPage function and it worked as expected.
$(window).unbind('beforeunload', ReturnMessage);
window.location.href=(page + id);
I hope this helps someone else.