2016-08-28 96 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事件偵聽器中調試並檢查調用。 –