2016-12-07 10 views
0

Я пытаюсь создать удалить подтверждение в мое приложение с помощью sweetalert, вот что я сделал до сих пор ..Удалить подтверждение с помощью sweetalert?

Вид:

<div class="box-button"> 
    {!! Form::open(['method' => 'POST', 'class' => 'deleteedition', 'action' => ['[email protected]', $edition->id]]) !!} 
    <input type="hidden" name="_method" value="DELETE"> 
    <input type="hidden" name="_token" value="{{ csrf_token() }}" /> 
    {!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm', 'id'=>'deleteedition1']) !!} 
    {!! Form::close() !!} 
</div> 

JS:

<script> 
      $("#deleteedition1").on("click", function() { 
       swal({ 
        title: "Are you sure?", 
        text: "You will not be able to recover this lorem ipsum!", type: "warning", 
        showCancelButton: true, 
        confirmButtonColor: "#DD6B55", 
        confirmButtonText: "Yes, delete it!", 
        closeOnConfirm: false 
       }, 
         function() { 
          $(".deleteedition").submit(); 
         }); 
      }); 
     </script> 

В проблема в том, что когда я нажимаю кнопку «Удалить», она будет продолжать удалять файл, даже если я не подтвержу его. Может кто-нибудь, пожалуйста, скажите мне, что я сделал неправильно? Спасибо за помощь!

Полный вид таблицы:

<table class="table table-borderless table-responsive" style="table-layout: fixed;"> 
          <thead> 
           <tr> 
            <th style="overflow: hidden;"></th> 

            @if (Auth::check() && Auth::user()->level == 'admin') 
            <th style="width: 130px;"></th> 
            @endif 

           </tr> 
          </thead> 
          <tbody> 
           <?php foreach ($edition_list as $edition): ?> 
            <tr> 
             <td style="overflow: hidden;"><a href="{{ url('edition/' . $edition->id) }}">Volume {{ $edition->volume }}, Nomor {{ $edition->number }} ({{ Carbon\Carbon::parse($edition->start)->format('F, Y') }})</a> 
              @if (Auth::check() && Auth::user()->status == '1') 
              @if (Carbon\Carbon::now()->between(Carbon\Carbon::parse($edition->start), Carbon\Carbon::parse($edition->limit))) 
              <p style="font-size: 10px; color: red;">Edisi aktif periode : {{ Carbon\Carbon::parse($edition->start)->format('j F Y') }} sampai {{ Carbon\Carbon::parse($edition->limit)->format('j F Y') }}</p> 
              @else 
              <p></p> 
              @endif 
              @endif 
             </td> 

             @if (Auth::check() && Auth::user()->level == 'admin') 
             <td style="overflow: hidden; width: 210px;"> 
              <div class="box-button"> 
               {{ link_to('edition/' . $edition->id . '/edit', 'Edit', ['class' => 'btn btn-warning btn-sm']) }} 
              </div> 
              <div class="box-button"> 
               {!! Form::open(['method' => 'POST', 'class' => 'deleteedition', 'action' => ['[email protected]', $edition->id]]) !!} 
               <input type="hidden" name="_method" value="DELETE"> 
               <input type="hidden" name="_token" value="{{ csrf_token() }}" /> 
               {!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm', 'id'=>'deleteedition1']) !!} 
               {!! Form::close() !!} 
              </div> 
             </td> 
             @endif 
            </tr> 
           <?php endforeach ?> 
          </tbody> 
         </table> 

ответ

1

В основном вы используете Еогеасп ($ edition_list в $ редакции) цикл, а затем жестко прописывать ид в {!!Form::submit}} как id=deleteedition1, который будет означать тот же идентификатор для всех удаляемых кнопок в Таблица.

Вместо этого вы могли бы попытаться сгенерировать форму идентификаторы динамически и на кнопку отправки вы можете иметь ссылку с помощью атрибута данных файла, как

<div class="box-button"> 
    {!! Form::open(['method' => 'POST', 'class' => "deleteedition edition", 'id'=>'edition-'.$edition->id, 'action' => ['[email protected]', $edition->id]]) !!} 
     <input type="hidden" name="_method" value="DELETE"> 
     <input type="hidden" name="_token" value="{{ csrf_token() }}" /> 
     {!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm delete-edition-btn', 'data-file'=>"edition-".$edition->id]) !!} 
    {!! Form::close() !!} 
</div> 

Тогда в сценарии

<script> 
    $(".delete-edition-btn").on("click", function (event) { 
     event.preventDefault(); 
     var file= '#'+this.attr('data-file'), 
      formId='form'+file, 
      parent=this.parents(formId); 
     swal({ 
      title: "Are you sure?", 
      text: "You will not be able to recover this lorem ipsum!", type: "warning", 
      showCancelButton: true, 
      confirmButtonColor: "#DD6B55", 
      confirmButtonText: "Yes, delete it!", 
      closeOnConfirm: false 
     }, 
     function() { 
      $(parent).submit(); 
     }); 
    }); 
</script> 

Or 
//here you don't depend upon dynamic ids but use the jQuery closest() 
<script> 
    $(".delete-edition-btn").on("click", function(event){ 
     event.preventDefault(); 

     swal({ 
      title: "Are you sure?", 
      text: "You will not be able to recover this lorem ipsum!", type: "warning", 
      showCancelButton: true, 
      confirmButtonColor: "#DD6B55", 
      confirmButtonText: "Yes, delete it!", 
      closeOnConfirm: false 
     }, 
     function(){ 
      // Use closest() to find the correct form in the DOM 
      $(this).closest("form.deleteedition").submit(); 
     }); 
    }); 
0

Try с помощью preventDefault() как:

<script> 
    $("#deleteedition1").on("click", function (event) { 
     event.preventDefault(); 
     swal({ 
      title: "Are you sure?", 
      text: "You will not be able to recover this lorem ipsum!", type: "warning", 
      showCancelButton: true, 
      confirmButtonColor: "#DD6B55", 
      confirmButtonText: "Yes, delete it!", 
      closeOnConfirm: false 
     }, 
     function() { 
      $(".deleteedition").submit(); 
     }); 
    }); 
</script> 
+0

он работал, но это удалит весь файл в списке, а не только один файл, предупреждение по умолчанию с помощью 'return confirm()' отлично работает и будет удалять только выбранный список. :/ –

0

Используйте jQuery's preventDefault(), чтобы предотвратить форму от представления, как это:

$("#deleteedition1").on("click", function (e) { 

    e.preventDefault(); <-------- here 

    swal({ 
     title: "Are you sure?", 
     text: "You will not be able to recover this lorem ipsum!", type: "warning", 
     showCancelButton: true, 
     confirmButtonColor: "#DD6B55", 
     confirmButtonText: "Yes, delete it!", 
     closeOnConfirm: false 
    }, 
    function() { 
     // Use closest() to find the correct form in the DOM 
     $(this).closest("form.deleteedition").submit(); 
    }); 
}); 

Вы можете использовать JQuery-х closest() метод, чтобы найти правильный файл из HTML DOM.

Согласно Jquery Docs: Если этот метод вызывается, действие по умолчанию события не будет срабатывать

Надежда это помогает!

+0

он работал, но он удалит весь файл в списке, а не только один файл, предупреждение по умолчанию с помощью 'return confirm()' отлично работает и будет удалять только выбранный список. :/ –

+0

Я не понял, где находится список файлов? –

+0

Что значит «где»? это запись данных в таблице с действием кнопки удаления в каждой отдельной записи. Я не могу это объяснить, так как мой английский не так хорош –

0

Попробуйте это, вы обрабатываете событие отправки всей вашей формы удаления. И, если swal подтвердится, форма представит

$('.deleteedition').on('submit',function(){ 
    return swal({ 
     title: "Are you sure?", 
     text: "You will not be able to recover this lorem ipsum!", type: "warning", 
     showCancelButton: true, 
     confirmButtonColor: "#DD6B55", 
     confirmButtonText: "Yes, delete it!", 
     closeOnConfirm: false 
    }, 
    function() { 
     // Use closest() to find the correct form in the DOM 
     //$(this).closest("form.deleteedition").submit(); 
     return true; 
    }); 
}) 
+0

Не должно быть '$ (this).submit() ', поскольку вы обрабатываете событие отправки в самой форме? Пожалуйста, поправьте меня, если я ошибаюсь. – Donkarnash

+0

, когда вы обрабатываете submit, вам не нужно использовать $ (this) .submit(), потому что это вызовет событие отправки, и у вас будет рекурсия. Вы должны вернуть true (submit) или false (ничего не делать) – mikrafizik

+0

Хорошо, спасибо за разъяснение. – Donkarnash