admin管理员组文章数量:1300200
I have a very long survey and I want to prevent the user from clicking the back button and losing all of their data. So far I have an alert that tells them they will lose all the data but when they submit the form to process the page it will pop up with the alert. Is there a way I can disable the alert only when they press the submit button? This is the method I am using to create the alert:
window.onbeforeunload = function() { return "Your work will be lost."; };
I have a very long survey and I want to prevent the user from clicking the back button and losing all of their data. So far I have an alert that tells them they will lose all the data but when they submit the form to process the page it will pop up with the alert. Is there a way I can disable the alert only when they press the submit button? This is the method I am using to create the alert:
window.onbeforeunload = function() { return "Your work will be lost."; };
Share
Improve this question
asked Feb 12, 2014 at 21:17
Yamaha32088Yamaha32088
4,16310 gold badges53 silver badges105 bronze badges
2
- Change your method to have it check if the cause of leaving the page was the form. If it was from the form, return nothing rather than a string. – Kevin B Commented Feb 12, 2014 at 21:19
- You'll need to bind your submit button to a javascript function and then in the function you can write logic to show the alert...For your help you can see this ..stackoverflow./questions/1947263/… – tgpatel Commented Feb 12, 2014 at 21:59
4 Answers
Reset to default 7You can set the beforeunload listener in this way:
var preventUser = function() {
return "Your work will be lost";
}
window.addEventListener('beforeunload',preventUser);
And then, when the user submit the form, you can remove the listener in this way:
function onSubmitForm(){
window.removeEventListener('beforeunload',preventUser);
}
For example:
<button onclick="onSubmitForm()">Submit Form</button>
i think you have to write that function, 'function() { return "Your work will be lost."; };' inside your onClick event of back button. And remove that line 'window.onbeforeunload = function() { return "Your work will be lost."; };'. I think, it will work fine...
window.onbeforeunload will get triggered even on normal tab or link clicks in addition to the browser's button clicks. I didn't find any trigger exclusive to the browser's back or forward clicks.
After trying so many plex way, I get this solution.
window.onbeforeunload = function () {
return 'Are you sure? Your work will be lost.';
};
$(document).on("submit", "form", function () {
window.onbeforeunload = null;
});
本文标签:
版权声明:本文标题:javascript - Added alert for when user clicks back button but now I want to remove it when submitting the form - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741653677a2390628.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论