Potwierdź usunięcie w modal / dialog za pomocą Twitter Bootstrap?

Mam tabelę HTML wierszy powiązanych z wierszami bazy danych. Chciałbym mieć link "Usuń wiersz" dla każdego wiersza, ale chciałbym wcześniej potwierdzić z użytkownikiem.

Czy jest jakiś sposób, aby to zrobić za pomocą okna modalnego Twitter Bootstrap?

Author: informatik01, 2012-01-24

12 answers

Pobierz przepis

Do tego zadania możesz użyć już dostępnych wtyczek i rozszerzeń bootstrap. Lub możesz zrobić własne wyskakujące okienko z potwierdzeniem za pomocą 3 linie kodu. Zobacz też

Powiedzmy, że mamy takie linki (Uwaga data-href zamiast href) lub przyciski, dla których chcemy mieć potwierdzenie delete:

<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>

<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
    Delete record #54
</button>

Tutaj #confirm-delete wskazuje na modalny Popup div w Twoim HTML. Powinien mieć przycisk" OK " skonfigurowany tak:

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                ...
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>

Teraz potrzebujesz tylko tego mały javascript, aby potwierdzić akcję delete:

$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});

Tak dalej show.bs.modal przycisk usuwania zdarzeń href jest ustawiony na adres URL z odpowiednim ID rekordu.

Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview


Przepis POST

Zdaję sobie sprawę, że w niektórych przypadkach może być konieczne wykonanie żądania POST lub DELETE, a następnie GET. To wciąż dość proste, bez zbyt dużo kodu. Spójrz na demo poniżej z tym podejście:

// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {

  var $modalDiv = $(e.delegateTarget);
  var id = $(this).data('recordId');

  $modalDiv.addClass('loading');
  $.post('/api/record/' + id).then(function() {
     $modalDiv.modal('hide').removeClass('loading');
  });
});

// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
  var data = $(e.relatedTarget).data();
  $('.title', this).text(data.recordTitle);
  $('.btn-ok', this).data('recordId', data.recordId);
});

// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {

  var $modalDiv = $(e.delegateTarget);
  var id = $(this).data('recordId');

  $modalDiv.addClass('loading');
  setTimeout(function() {
    $modalDiv.modal('hide').removeClass('loading');
  }, 1000);

  // In reality would be something like this
  // $modalDiv.addClass('loading');
  // $.post('/api/record/' + id).then(function() {
  //   $modalDiv.modal('hide').removeClass('loading');
  // });
});

// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
  var data = $(e.relatedTarget).data();
  $('.title', this).text(data.recordTitle);
  $('.btn-ok', this).data('recordId', data.recordId);
});
.modal.loading .modal-content:before {
  content: 'Loading...';
  text-align: center;
  line-height: 155px;
  font-size: 20px;
  background: rgba(0, 0, 0, .8);
  position: absolute;
  top: 55px;
  bottom: 0;
  left: 0;
  right: 0;
  color: #EEE;
  z-index: 1000;
}
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
      </div>
      <div class="modal-body">
        <p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>
        <p>Do you want to proceed?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger btn-ok">Delete</button>
      </div>
    </div>
  </div>
</div>
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">
        Delete "The first one", #23
    </a>
<br />
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">
  Delete "Something cool", #54
</button>

Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview


Bootstrap 2.3

Oto Oryginalna wersja kodu, który zrobiłem, gdy odpowiadałem na to pytanie dotyczące Bootstrap 2.3 modal.

$('#modal').on('show', function() {
    var id = $(this).data('id'),
        removeBtn = $(this).find('.danger');
    removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});

Demo: http://jsfiddle.net/MjmVr/1595/

 410
Author: dfsq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-02 07:37:58

Http://bootboxjs.com/ - najnowsze prace z Bootstrap 3.0.0

Najprostszy możliwy przykład:

bootbox.alert("Hello world!"); 

Ze strony:

Biblioteka udostępnia trzy metody mające na celu naśladowanie ich natywnych odpowiedników JavaScript. Ich dokładne podpisy metod są elastyczne, ponieważ każda z nich może przyjmować różne parametry, aby dostosować etykiety i określić domyślne, ale najczęściej nazywa się je tak: {]}

bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)

Oto jego fragment w akcji (kliknij " Uruchom kod fragment " poniżej):

$(function() {
  bootbox.alert("Hello world!");
});
<!-- required includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

<!-- bootbox.js at 4.4.0 -->
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>
 160
Author: Rifat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-24 19:19:15
  // ---------------------------------------------------------- Generic Confirm  

  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal hide fade">' +    
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    });

    confirmModal.modal('show');     
  };

  // ---------------------------------------------------------- Confirm Put To Use

  $("i#deleteTransaction").live("click", function(event) {
    // get txn id from current table row
    var id = $(this).data('id');

    var heading = 'Confirm Transaction Delete';
    var question = 'Please confirm that you wish to delete transaction ' + id + '.';
    var cancelButtonTxt = 'Cancel';
    var okButtonTxt = 'Confirm';

    var callback = function() {
      alert('delete confirmed ' + id);
    };

    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

  });
 31
Author: jousby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-12 13:04:08

Zdałbym sobie sprawę, że to bardzo stare pytanie, ale ponieważ dziś zastanawiałem się nad bardziej efektywną metodą obsługi modali bootstrap. Poszperałem trochę i znalazłem coś lepszego niż rozwiązania pokazane powyżej, które można znaleźć pod tym linkiem: {]}

Http://www.petefreitag.com/item/809.cfm

Najpierw załaduj jquery

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');

        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

To po prostu zadaj pytanie / potwierdzenie href:

<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>

W ten sposób modal potwierdzenia jest o wiele bardziej uniwersalny i tak to może być łatwo ponownie użyty w innych częściach witryny.

 29
Author: Arjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-07 10:39:52

Dzięki rozwiązaniu @ Jousby , udało mi się również uruchomić moje, ale okazało się, że musiałem poprawić nieco znaczniki Modalne Bootstrap jego rozwiązania, aby renderował poprawnie, jak pokazano w oficjalnych przykładach .

Oto moja zmodyfikowana wersja funkcji generic confirm, która działała poprawnie:

/* Generic Confirm func */
  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal fade">' +        
          '<div class="modal-dialog">' +
          '<div class="modal-content">' +
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#!" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#!" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
          '</div>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    }); 

    confirmModal.modal('show');    
  };  
/* END Generic Confirm func */
 18
Author: nemesisfixx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:05

Uważam, że to przydatne i łatwe w użyciu, a do tego wygląda ładnie: http://maxailloud.github.io/confirm-bootstrap/.

Aby go użyć, Dołącz .plik js na twojej stronie następnie uruchom:

$('your-link-selector').confirmModal();

Istnieją różne opcje, które można zastosować do niego, aby wyglądał lepiej podczas robienia tego, aby potwierdzić usunięcie, używam:

$('your-link-selector').confirmModal({
    confirmTitle: 'Please confirm',
    confirmMessage: 'Are you sure you want to delete this?',
    confirmStyle: 'danger',
    confirmOk: '<i class="icon-trash icon-white"></i> Delete',
    confirmCallback: function (target) {
         //perform the deletion here, or leave this option
         //out to just follow link..
    }
});
 10
Author: Mark Rhodes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-20 10:38:09

Z łatwością poradzę sobie z tego typu zadaniami używając bootboxa.biblioteka js. Na początku musisz dołączyć plik bootbox JS. Następnie w funkcji obsługi zdarzeń wpisz następujący kod:

    bootbox.confirm("Are you sure to want to delete , function(result) {

    //here result will be true
    // delete process code goes here

    });

Official bootboxjs site

 4
Author: karim_fci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-27 13:10:42

Poniższe rozwiązanie jest lepsze niż bootbox.js, Ponieważ

    Może zrobić wszystko bootbox.js potrafi;
  • składnia użycia jest prostsza
  • pozwala elegancko kontrolować kolor wiadomości za pomocą "błąd", "ostrzeżenie " lub"informacja"
  • Bootbox ma 986 linii, mój tylko 110 linii

Digimango.messagebox.js :

const dialogTemplate = '\
    <div class ="modal" id="digimango_messageBox" role="dialog">\
        <div class ="modal-dialog">\
            <div class ="modal-content">\
                <div class ="modal-body">\
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\
                </div>\
                <div class ="modal-footer">\
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\
                </div>\
            </div>\
        </div>\
    </div>';


// See the comment inside function digimango_onOkClick(event) {
var digimango_numOfDialogsOpened = 0;


function messageBox(msg, significance, options, actionConfirmedCallback) {
    if ($('#digimango_MessageBoxContainer').length == 0) {
        var iDiv = document.createElement('div');
        iDiv.id = 'digimango_MessageBoxContainer';
        document.getElementsByTagName('body')[0].appendChild(iDiv);
        $("#digimango_MessageBoxContainer").html(dialogTemplate);
    }

    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;

    if (options == null) {
        okButtonName = 'OK';
        cancelButtonName = null;
        showTextBox = null;
        textBoxDefaultText = null;
    } else {
        okButtonName = options.okButtonName;
        cancelButtonName = options.cancelButtonName;
        showTextBox = options.showTextBox;
        textBoxDefaultText = options.textBoxDefaultText;
    }

    if (showTextBox == true) {
        if (textBoxDefaultText == null)
            $('#digimango_messageBoxTextArea').val('');
        else
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);

        $('#digimango_messageBoxTextArea').show();
    }
    else
        $('#digimango_messageBoxTextArea').hide();

    if (okButtonName != null)
        $('#digimango_messageBoxOkButton').html(okButtonName);
    else
        $('#digimango_messageBoxOkButton').html('OK');

    if (cancelButtonName == null)
        $('#digimango_messageBoxCancelButton').hide();
    else {
        $('#digimango_messageBoxCancelButton').show();
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);
    }

    $('#digimango_messageBoxOkButton').unbind('click');
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);

    $('#digimango_messageBoxCancelButton').unbind('click');
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);

    var content = $("#digimango_messageBoxMessage");

    if (significance == 'error')
        content.attr('class', 'text-danger');
    else if (significance == 'warning')
        content.attr('class', 'text-warning');
    else
        content.attr('class', 'text-success');

    content.html(msg);

    if (digimango_numOfDialogsOpened == 0)
        $("#digimango_messageBox").modal();

    digimango_numOfDialogsOpened++;
}

function digimango_onOkClick(event) {
    // JavaScript's nature is unblocking. So the function call in the following line will not block,
    // thus the last line of this function, which is to hide the dialog, is executed before user
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do
    // not execute the last line in this function.
    if (typeof (event.data.callback) != 'undefined')
        event.data.callback($('#digimango_messageBoxTextArea').val());

    digimango_numOfDialogsOpened--;

    if (digimango_numOfDialogsOpened == 0)
        $('#digimango_messageBox').modal('hide');
}

function digimango_onCancelClick() {
    digimango_numOfDialogsOpened--;

    if (digimango_numOfDialogsOpened == 0)
        $('#digimango_messageBox').modal('hide');
}

Aby użyć Digimango.messagebox.js :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>A useful generic message box</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>

    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>


    <script type="text/javascript">
        function testAlert() {
            messageBox('Something went wrong!', 'error');
        }

        function testAlertWithCallback() {
            messageBox('Something went wrong!', 'error', null, function () {
                messageBox('OK clicked.');
            });
        }

        function testConfirm() {
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });
            });
        }

        function testPrompt() {
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {
                messageBox('User entered "' + userInput + '".');
            });
        }

        function testPromptWithDefault() {
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {
                messageBox('User entered "' + userInput + '".');
            });
        }

    </script>
</head>

<body>
    <a href="#" onclick="testAlert();">Test alert</a> <br/>
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>
    <a href="#" onclick="testPrompt();">Test prompt</a><br />
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />
</body>

</html>
Tutaj wpisz opis obrazka
 2
Author: Silly Dude,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-30 01:44:28

Jeśli chodzi o odpowiednio duży projekt, możemy potrzebować czegoś nadającego się do ponownego użycia. To jest coś, z czym przyszedłem z pomocą SO.

ConfirmDelete.jsp

<!-- Modal Dialog -->
<div class="modal fade" id="confirmDelete" role="dialog" aria-labelledby="confirmDeleteLabel"
 aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"
                    aria-hidden="true">&times;</button>
            <h4 class="modal-title">Delete Parmanently</h4>
        </div>
        <div class="modal-body" style="height: 75px">
            <p>Are you sure about this ?</p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-danger" id="confirm-delete-ok">Ok
            </button>
        </div>
    </div>
</div>

<script type="text/javascript">

    var url_for_deletion = "#";
    var success_redirect = window.location.href;

$('#confirmDelete').on('show.bs.modal', function (e) {
    var message = $(e.relatedTarget).attr('data-message');
    $(this).find('.modal-body p').text(message);
    var title = $(e.relatedTarget).attr('data-title');
    $(this).find('.modal-title').text(title);

    if (typeof  $(e.relatedTarget).attr('data-url') != 'undefined') {
        url_for_deletion = $(e.relatedTarget).attr('data-url');
    }
    if (typeof  $(e.relatedTarget).attr('data-success-url') != 'undefined') {
        success_redirect = $(e.relatedTarget).attr('data-success-url');
    }

});

<!-- Form confirm (yes/ok) handler, submits form -->
$('#confirmDelete').find('.modal-footer #confirm-delete-ok').on('click', function () {
    $.ajax({
        method: "delete",
        url: url_for_deletion,
    }).success(function (data) {
        window.location.href = success_redirect;
    }).fail(function (error) {
        console.log(error);
    });
    $('#confirmDelete').modal('hide');
    return false;
});
<script/>

ReusingPage.jsp

<a href="#" class="table-link danger"
data-toggle="modal"
data-target="#confirmDelete"
data-title="Delete Something"
data-message="Are you sure you want to inactivate this something?"
data-url="client/32"
id="delete-client-32">
</a>
<!-- jQuery should come before this -->
<%@ include file="../some/path/confirmDelete.jsp" %>

Uwaga: Ten używa metody HTTP delete dla żądania usunięcia, można zmienić go z javascript lub, można wysłać go za pomocą atrybutu danych, jak w data-title lub data-url itp., do obsługi każdego żądania.

 1
Author: Maleen Abewardana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-18 18:40:30

Jeśli chcesz to zrobić najprostszym skrótem, możesz to zrobić za pomocą Ta wtyczka.


Ale ten plugin jest alternatywną implementacją używającą Bootstrap Modal. A prawdziwa implementacja Bootstrap jest również bardzo łatwa, więc nie lubię używać tej wtyczki, ponieważ dodaje nadmiar zawartości JS na stronie, co spowolni czas ładowania strony.


Idea

Lubię to realizować sam w ten sposób-

  1. If user kliknijs na przycisku, aby usunąć element z listy, a następnie wywołanie JS umieści Item ID (lub inne istotne dane) w formularzu w modalu.
  2. Następnie w wyskakującym okienku pojawią się 2 przyciski do potwierdzenia.

    • Tak. w ten sposób można uzyskać więcej informacji na ten temat.]}
    • Nie. po prostu odrzuci modal

Kod będzie wyglądał tak (używając Bootstrap)-

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
$(document).ready(function()
{
    $("button").click(function()
    {
        //Say - $('p').get(0).id - this delete item id
        $("#delete_item_id").val( $('p').get(0).id );
        $('#delete_confirmation_modal').modal('show');
    });
});
</script>

<p id="1">This is a item to delete.</p>

<button type="button" class="btn btn-danger">Delete</button>

<!-- Delete Modal content-->

<div class="modal fade" id="delete_confirmation_modal" role="dialog" style="display: none;">
	<div class="modal-dialog" style="margin-top: 260.5px;">
				<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">×</button>
				<h4 class="modal-title">Do you really want to delete this Category?</h4>
			</div>
			<form role="form" method="post" action="category_delete" id="delete_data">
				<input type="hidden" id="delete_item_id" name="id" value="12">
				<div class="modal-footer">
					<button type="submit" class="btn btn-danger">Yes</button>
					<button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
				</div>
			</form>
		</div>

	</div>
</div>

Należy zmienić działanie formularza zgodnie z wymaganiami.

Happy coading:)

 1
Author: Abrar Jahin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-06 03:24:09

Możesz spróbować bardziej wielokrotnego użytku my solution z callback funkcja. W tej funkcji możesz użyć żądania POST lub logiki. Używane biblioteki: JQuery 3 > i Bootstrap 3 > .

Https://jsfiddle.net/axnikitenko/gazbyv8v/

Kod Html do testu:

...
<body>
    <a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
</body>
...

Javascript:

$(function () {
    function remove() {
        alert('Remove Action Start!');
    }
    // Example of initializing component data
    this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
        'remove-btn-a-id', {
            txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
            txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
        });
    this.cmpModalRemove.initialize();
});

//----------------------------------------------------------------------------------------------------------------------
// COMPONENT SCRIPT
//----------------------------------------------------------------------------------------------------------------------
/**
 * Script processing data for confirmation dialog.
 * Used libraries: JQuery 3> and Bootstrap 3>.
 *
 * @param name unique component name at page scope
 * @param callback function which processing confirm click
 * @param actionBtnId button for open modal dialog
 * @param text localization data, structure:
 *              > txtModalHeader - text at header of modal dialog
 *              > txtModalBody - text at body of modal dialog
 *              > txtBtnConfirm - text at button for confirm action
 *              > txtBtnCancel - text at button for cancel action
 *
 * @constructor
 * @author Aleksey Nikitenko
 */
function ModalConfirmationComponent(name, callback, actionBtnId, text) {
    this.name = name;
    this.callback = callback;
    // Text data
    this.txtModalHeader =   text.txtModalHeader;
    this.txtModalBody =     text.txtModalBody;
    this.txtBtnConfirm =    text.txtBtnConfirm;
    this.txtBtnCancel =     text.txtBtnCancel;
    // Elements
    this.elmActionBtn = $('#' + actionBtnId);
    this.elmModalDiv = undefined;
    this.elmConfirmBtn = undefined;
}

/**
 * Initialize needed data for current component object.
 * Generate html code and assign actions for needed UI
 * elements.
 */
ModalConfirmationComponent.prototype.initialize = function () {
    // Generate modal html and assign with action button
    $('body').append(this.getHtmlModal());
    this.elmActionBtn.attr('data-toggle', 'modal');
    this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
    // Initialize needed elements
    this.elmModalDiv =  $('#'+this.getModalDivId());
    this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
    // Assign click function for confirm button
    var object = this;
    this.elmConfirmBtn.click(function() {
        object.elmModalDiv.modal('toggle'); // hide modal
        object.callback(); // run callback function
    });
};

//----------------------------------------------------------------------------------------------------------------------
// HTML GENERATORS
//----------------------------------------------------------------------------------------------------------------------
/**
 * Methods needed for get html code of modal div.
 *
 * @returns {string} html code
 */
ModalConfirmationComponent.prototype.getHtmlModal = function () {
    var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
    result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
    result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
    result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
    result += '<div class="modal-footer">';
    result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
    result += this.txtBtnCancel + '</button>';
    result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
    result += this.txtBtnConfirm + '</button>';
    return result+'</div></div></div></div>';
};

//----------------------------------------------------------------------------------------------------------------------
// UTILITY
//----------------------------------------------------------------------------------------------------------------------
/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getModalDivId = function () {
    return this.name + '-modal-id';
};

/**
 * Get id element with name prefix for this component.
 *
 * @returns {string} element id
 */
ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
    return this.name + '-confirm-btn-id';
};
 1
Author: Alexey Nikitenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-20 14:18:07

Dodaj przepis z nawigacją do strony docelowej i Pliku ostrza wielokrotnego użytku

Odpowiedź Dfsq jest bardzo miła. Zmodyfikowałem go trochę, aby pasował do moich potrzeb: w rzeczywistości potrzebowałem modala do sprawy, że po kliknięciu użytkownik będzie również nawigowany do odpowiedniej strony. Wykonanie zapytania asynchronicznie nie zawsze jest tym, czego potrzebujemy.

Używając Blade utworzyłem plik resources/views/includes/confirmation_modal.blade.php:

<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>{{ $headerText }}</h4>
            </div>
            <div class="modal-body">
                {{ $bodyText }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <form action="" method="POST" style="display:inline">
                    {{ method_field($verb) }}
                    {{ csrf_field() }}
                    <input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $('#confirmation-modal').on('show.bs.modal', function(e) {
        href = $(e.relatedTarget).data('href');

        // change href of button to corresponding target
        $(this).find('form').attr('action', href);
    });
</script>

Teraz korzystanie z niego jest proste:

<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>

Niewiele się tu zmieniło, a modal może być zawarte Tak:

@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])

Po prostu wstawiając czasownik, używa go. W ten sposób wykorzystuje się również CSRF.

Pomogło mi, może pomogło komuś innemu.
 1
Author: IceFire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-25 14:34:27