I would like to create a confirmation for handling changes of a page. For example gmail or other plenty of other websites has a system that when you change a field in the page and when you would like to leave page or clear the form inputs , the site will create a confirmation dialogue which help you to save the changes that you have forgotten. Here is my solution but I wonder whether there is a better way or not. Also the project is JSF project and using primefaces 3.4
Solution:
1.Create a global js variable
var isChanges = false;
- Put the handler on all input fields onchanges method.
< p:inputText value=”#{someMB.someValue}” id=”id” onkeydown=”isChanges=true”>< /p:inputText>
or
< p:selectOneMenu value=”#{someMB.someValue}” id=”#{cc.attrs.id}” >
< p:ajax event=”change” onsuccess=”isChanges=true” />
< /p:selectOneMenu>
etc….
Detect whether user leave page or clear form inputs:
< script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(isChanged && window.confirm("sometext")){
// Call servers save method
}
}
< /script>
In my web application, I do this:
noHashclassnoHashclassThen, when a user tries to navigate away, I recompute the hash as described above and see if the hashes are different, if they are I prompt the user for confirmation before leaving the page.
Please note that this is all done using javascript, so is independent of your server side script language.