2011-03-28 40 views
2

隨着我的CakePHP的登記表,一旦點擊提交按鈕,我只是想顯示的Javascript確認對話框,應該像:CakePHP的JavaScript的confirm對話框表單提交取消不工作

  • 如果按下確定,應提交形式
  • 如果按下取消,不應該去提交行動

但在這裏,當我按下取消,雖然它被提交。不知道爲什麼?

CakePHP的表單代碼:

<?php echo $form->create('Noncompetitor', array('type' => 'file', 'url' => '/register', 'onSubmit' => 'confirmfrmSubmit();'));?>

我的JS代碼:

`函數confirmfrmSubmit(){

var agree=confirm("Are you sure you wish to continue?"); 

if (agree) 
    return true ; 
else 
    return false ; 

} `

請讓我知道,如果你的研究員對我有一些想法噸。

謝謝!

回答

4

更新:貸記bicycle修復我的損壞的回調。詳情請參閱下文。 (而且是個大樹莓到StackO爲不允許回答筆者說了算上接受一個編輯)


下面是使用jQuery的解決方案:

<?php 
    $this->Html->scriptBlock(" 
     jQuery(function($){ 
      $('form.noncompetitor').submit(function(event){ 
       if (!confirm('Are you sure?')) { return false; } 
      }); 
     }); 
    ",array('inline'=>false)); // inline => false will put this snippet in the DOM's head. 

    echo $this->Form->create('Noncompetitor',array(
     'type'=>'file','url'=>'/register', 
     'default'=>false,'class'=>'noncompetitor' 
    )); 

    /* The rest of your form */ 
+0

我不要編輯,因爲他們可能會像往常一樣拒絕它。但是這不斷要求確認。替換'event.preventDefault(); if(confirm('Are you sure?')){ $(this).submit(); ('confirm('Are you sure?')){ \t return false; }' – bicycle 2013-08-17 06:49:29

+0

隨意建議編輯,我會接受它,我發誓! Naaah, – 2013-08-18 22:58:45

+0

,仍然拒絕。看到http://stackoverflow.com/review/suggested-edits/2762110 – bicycle 2013-08-21 06:21:47

1

我發現了一個很簡單的解決方案此查詢:

<?php echo $form->create('ModelName', array('type' => 'file', 'url' => 'url', 'name' => 'frmRegister', 'onsubmit' => 'validatefrm(); return false;')); ?>

隨着的onsubmit功能,我只是定義'validatefrm();返回false;'

function validatefrm(){ // my condition, when i needs it to submitted document.frmRegister.submit(); return true; }

,發現它的工作接吻:)

讓我知道,如果它可以幫助你。

8

也可以用更簡單的方法,試試這個:

$this->Form->create('Request',array('onsubmit'=>'return confirm("are you sure?");')) 
+1

最好使用上面的jquery方法,並把它放在一個單獨的.js文件中。您應該儘可能在html中限制javascript。 – bicycle 2013-08-17 06:52:33

+0

我完全同意@bicycle。突出的JS是一種氣味。 – 2013-08-18 23:00:11

2

我想你的函數失敗,因爲你從來沒有真正從返回的confirmfrmSubmit值()。

嘗試添加返回部分給的onsubmit領域,像這樣:

<?php echo $form->create('Noncompetitor', array('type' => 'file', 'url' => '/register', 'onSubmit' => 'return confirmfrmSubmit();'));?> 

你的JS代碼應工作,因爲它是,這個問題就是這樣的確認值永遠不會被傳遞到窗體時onSubmit處理程序被調用。

P.S.請注意,您可以在JS代碼中執行以下操作:

return confirm("Text"); 

希望這會有所幫助。

1

你實際上是99%的方式,你只需要在你調用驗證函數之前添加'return'。

<?php echo $form->create('Noncompetitor', array(
     'type' => 'file', 
     'url' => '/register', 
     'onSubmit' => 'return confirmfrmSubmit();')); 
?> 

會這樣做。