JavaScript 确认删除

6

我正在创建一个简单的内容管理系统,以下是我的代码:

<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");
     }

但是当在确认对话框中点击取消时,表单仍然被提交并删除了所选文章。请指导应该怎么做。

7个回答

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。


2

建议使用 onSubmit 而不是 onClick


2

你想做的是类似这样的事情:

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

当表单通过type="submit"按钮提交时,将调用delete_confirm()函数。如果它返回true,则表单将被提交。如果返回false,则不会提交。

2
尝试使用AJAX从Javascript内调用PHP脚本。这意味着将输入按钮类型设置为button <input type="button" />,并更改onclick,以便在按下取消时返回false(与您所做的一样),或者在按下OK时运行AJAX脚本并在需要时重定向页面... 您可以在单独的文件中编写AJAX服务器端(PHP)脚本,并使用$_GET发送参数。

0

也许尝试使用:

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

0

delete_confirm() 在您的情况下必须始终返回false


0

您希望将删除确认功能作为表单的onsubmit属性。仅在输入元素上设置不足以实现此功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接