2016-08-28 65 views
1

我在视图中列出了类别。删除类别按钮也存在于工作中的视图中,并在点击时删除类别。Laravel 5.2 - Sweet Alert确认框

我想要做的是在删除一个类别之前,弹出一个甜蜜的提示对话框并要求确认。如果确认,应该转到定义的路线并删除类别。

的删除链接的定义是这样的:

<a id="delete-btn" href="{{ route('admin.categories.destroy', $category->id) }}" class="btn btn-danger">Delete</a>

和脚本的定义如下:

<script> 
    $(document).on('click', '#delete-btn', function(e) { 
     e.preventDefault(); 
     var link = $(this); 
     swal({ 
      title: "Confirm Delete", 
      text: "Are you sure to delete this category?", 
      type: "warning", 
      showCancelButton: true, 
      confirmButtonColor: "#DD6B55", 
      confirmButtonText: "Yes, delete it!", 
      closeOnConfirm: true 
     }, 
     function(isConfirm){ 
      if(isConfirm){ 
       window.location = link.attr('href'); 
      } 
      else{ 
       swal("cancelled","Category deletion Cancelled", "error"); 
      } 
     }); 
    }); 
</script> 

然而,当我点击删除按钮,它删除了类,但甜蜜的警报消息不会显示出来。

路线被定义为以下:

Route::get('/categories/destroy/{category}', [ 
    'uses' => '[email protected]', 
    'as' => 'admin.categories.destroy', 
]); 

和控制器函数被定义为:

public function destroy(Category $category) 
{ 

    $category->delete(); 

    //this alert is working fine. however, the confirmation alert should appear 
    //before this one, which doesn't 
    Alert::success('Category deleted successfully', 'Success')->persistent("Close"); 

    return redirect()->back(); 
} 

任何帮助,将不胜感激。谢谢。

回答

2

试试这个:

<script> 
    var deleter = { 

     linkSelector : "a#delete-btn", 

     init: function() { 
      $(this.linkSelector).on('click', {self:this}, this.handleClick); 
     }, 

     handleClick: function(event) { 
      event.preventDefault(); 

      var self = event.data.self; 
      var link = $(this); 

      swal({ 
       title: "Confirm Delete", 
       text: "Are you sure to delete this category?", 
       type: "warning", 
       showCancelButton: true, 
       confirmButtonColor: "#DD6B55", 
       confirmButtonText: "Yes, delete it!", 
       closeOnConfirm: true 
      }, 
      function(isConfirm){ 
       if(isConfirm){ 
        window.location = link.attr('href'); 
       } 
       else{ 
        swal("cancelled", "Category deletion Cancelled", "error"); 
       } 
      }); 

     }, 
    }; 

    deleter.init(); 
</script> 

编辑:在@格利扬 - 辛格 - 拉索的回答您的意见,我觉得你没有正确注入脚本刀片模板。如果您要扩展基本布局,请确保已包含该脚本或将其从子布局中取消。

+0

工作!非常感谢。 – byteseeker

0

以下面的方式写锚点。

<a href="#" customParam="URL">Delete</a> 

现在在URL中选择将href更改为customParam。

function (isConfirm) { 
    if (isConfirm) { 
     window.location = link.attr('customParam'); 
    } else { 
     swal("cancelled", "Category deletion Cancelled", "error"); 
    } 
} 

基本上在你的情况下,href和事件侦听器都是单击。

+0

没有工作。这一次甚至类别都没有被删除。 – byteseeker

+0

在jquery事件侦听器中调试并检查调用。 –