2011-07-16 115 views
6

正在創建一個簡單的CMS和我有以下的Javascript確認刪除

<input type="submit" value="delete" title="Delete Aricle(s)" id="delete_btn" onclick="delete_confirm()" /> 

<tbody> 
    <?php foreach ($articles as $article): ?> 
    <tr> 
    <td align="center"> 
    <input id="article_id"name="article[]" type="checkbox" value="<?php echo $article->id; ?>" /></td> 
    <td align="center"><?php echo anchor('admin/articles/edit/'.$article->id,$article->title); ?></td> 
    <td align="center"><?php echo $article->author; ?></td> 
    <td align="center"><?php echo $article->category; ?></td> 
    <td align="center"><?php published($article->post_status); ?></td> 
    <td align="center"><?php featured($article->featured); ?></td> 
    <td align="center"><?php echo $article->views; ?></td> 
    <td align="center"><?php echo $article->post_date; ?></td> 
    </tr> 
    <?php endforeach;?> 
    </tbody> 

上面的代碼被包裝在一個表單標籤

這是我的javascript代碼

function delete_confirm() { 
    var msg = confirm('Are you sure you want to delete the selected article(s)'); 
    if(msg == false) { 
     return false; 
    } 
} 

這是刪除在我的控制器中的功能

function articles_delete() { 
     //Load Model 
     $this->load->model("article_model"); 
     //Assign article id to variable 
     $checkbox = $_POST['article']; 
     //loop through selected checkbox 
     for($i = 0; $i < count($checkbox); $i++) { 
      //Call delete method of the article model 
      $this->article_model->delete($checkbox[$i]); 
     } 
     $this->session->set_flashdata("message","Article(s) Deleted"); 
     redirect("admin/articles","refresh"); 
    } 

但是當在確認對話框中點擊取消時,表格仍然被取消,所選文章被刪除。 請教個建議

回答

6

嘗試改變

<input type="submit" value="delete" title="Delete Aricle(s)" id="delete_btn" onclick="delete_confirm()" />

<input type="submit" value="delete" title="Delete Aricle(s)" id="delete_btn" onclick="return delete_confirm();" />

你正在運行的onclick函數內的delete_confirm()函數。你需要從onclick()函數本身返回false。

+0

工作感謝 – MrFoh

0

delete_confirm()在您的情況下必須始終返回false

2

你會想要做的是這樣的:

<form onsubmit="return delete_confirm();" ...> 
    <input ...> 
</form> 

當表單通過type="submit" - 按鈕提交,你delete_confirm() - 函數被調用。如果它返回true,表單被提交。如果它返回false,那不是。

0

您希望刪除確認功能是您的onsubmit表單屬性。將它放在輸入元素上是不夠的。

0

也許嘗試使用:

<a href="javascript: if(confirm('Relly?')) { document.getElementById('your_form').action='php.php'; document.getElementById('your_form').submit(); } ">Delete</a> 
2

嘗試使用AJAX來從內部JavaScript調用PHP腳本。

這意味着將輸入按鈕類型設置爲按鈕<input type="button" />並更改onclick,使得如果按下cancel,則返回false(如您所做的那樣),或者如果按下OK,則運行AJAX腳本並在需要時重定向頁面。 ..

您可以在單獨的文件中編寫AJAX服務器端(PHP)腳本,並使用$ _GET發送參數。