2014-03-28 62 views
2

我有一個表單,並且我希望在提交值之前用戶關閉頁面時要求確認。我已經嘗試了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

像'onbeforeunload =函數(){返回提示(「你確定?「); }' –

+0

onbeforeunload的作品,如果你不把你的代碼,我們不能幫你 – giammin

+0

您可能正在尋找: http://stackoverflow.com/questions/16606496/show-message-box-ext-window-beforeclose-事件 –

回答

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.'); 
    } 

}); 
+0

它不起作用。我不明白。我在用樹枝引擎呈現的模板中使用它。 – user3455230

+0

在那裏添加'return confirm'Leaving ...''(它在建議的編輯中)。 confirm關鍵字丟失。 – Zlatko

+0

@Zlatko沒有'確認'它的工作正常,對我來說,當我使用確認它不起作用!這是否爲你工作確認? –