我有一个表单,在提交值之前,我想在用户关闭页面时询问确认。我已经尝试了this question中描述的脚本,但它似乎不起作用:userSubmitted值数字总是如此,并且弹出窗口不会出现。
我的模板中的代码是:
<script>
window.onbeforeunload = function() {
if(!userSubmitted)
return 'Are you sure that you want to leave this page?';};
</script>
我控制器中的代码是:
$userSubmitted=false;
//...
$form->handleRequest($request);
if ($form->isValid()) {
$userSubmitted=true;
//...
return $this->render('DefaultBundle::formupload.html.twig', array(
'form' => $form->createView(), 'userSubmitted->$userSubmitted
));
//...
答案 0 :(得分:5)
var warn_on_unload = false; //default false
$('input,textarea,select').on('change', function () {
//making true when user types in , or select
warn_on_unload = true;
});
$(window).bind('beforeunload', function(){
//warns user if not saving form and closing or browsing other page
if(warn_on_unload)
{
return confirm('Leaving this page will cause any unsaved data to be lost.');
}
});