Как использовать Modal Bootstrap для подтверждения удаления да / нет? - PullRequest
0 голосов
/ 09 мая 2018

У меня есть модальное окно, которое должно подтвердить, хочет ли пользователь удалить запись или нет. До сих пор я получил это на работу, но у меня есть функция внутри функции. Это не рекомендуется, как я знаю в JavaScript, поэтому мне было интересно, есть ли другое решение, чтобы избежать этой проблемы? Вот пример:

var myJSON = {
  "customers": [{
      "id": 100,
      "first": "Mike",
      "last": "Johnson",
      "email": "mjohnson@gmail.com",
      "position": "Consultant"
    },
    {
      "id": 101,
      "first": "John",
      "last": "Dunn",
      "email": "jdunn@gmail.com",
      "position": "Programmer"
    },
    {
      "id": 109,
      "first": "Lisa",
      "last": "Morgan",
      "email": "lmorgan@gmail.com",
      "position": "Secretary"
    },
    {
      "id": 233,
      "first": "Kris",
      "last": "Bradley",
      "email": "kbradley@gmail.com",
      "position": "Programmer"
    },
    {
      "id": 57,
      "first": "Dave",
      "last": "Hart",
      "email": "dhart@gmail.com",
      "position": "Supervisor"
    }
  ]
};

$(document).ready(function() {
  generateTbl();
});

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "<div class='table-responsive'><table class='table table-striped' id='customers'><thead><tr><th>Customer ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Position</th><th>Delete</th></thead><tbody>";

  for (var key in jsonData) {
    buildTbl += "<tr id='row_" + jsonData[key].id + "'><td data-id='id'>" + $.trim(jsonData[key].id) + "</td>";
    buildTbl += "<td data-id='first'>" + $.trim(jsonData[key].first) + "</td>";
    buildTbl += "<td data-id='last'>" + $.trim(jsonData[key].last) + "</td>";
    buildTbl += "<td data-id='email'>" + $.trim(jsonData[key].email) + "</td>";
    buildTbl += "<td data-id='position'>" + $.trim(jsonData[key].position) + "</td>";
    buildTbl += "<td class='text-center'><button type='button' class='btn btn-default btn-sm customer_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
  }
  buildTbl += "</tbody></table></div>";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', ':button.customer_delete', deleteCustomer);

function deleteCustomer() {
  var recordID = $(this).closest('tr').attr('id'), // Get record ID.
    targetTr = $(this).parents('tr');

  $('#deleteModal').modal('show'); // Show delete modal box.
  $('.confirm_delete').on('click', function() {
    if (recordID) {
      var table = $('#customers').DataTable(); // Select DataTable by ID.
      table.row(targetTr).remove().draw(); // Remove record from DataTable.
    }
  });
}
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- *** Start: JS and CSS for DataTables. *** -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />


<div class="container">
  <div class="panel panel-primary">
    <div class="panel-heading">Welcome to Main Page</div>
    <div class="panel-body">
      <div id="customers_data" class="table-responsive"></div>
    </div>
  </div>
</div>
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" 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">Confirm Delete</h4>
      </div>
      <div class="modal-body" id="delete_modalBody">
        <p>You are about to delete customer record, this procedure is irreversible.</p>
        <p>Do you want to proceed?</p>
        <p class="debug-url"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default confirm_delete" data-dismiss="modal">Delete</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

Если кто-нибудь знает лучшее решение, пожалуйста, дайте мне знать.

Ответы [ 2 ]

0 голосов
/ 09 мая 2018

Определите ваш recordID вне области действия функции.

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

здесь

var myJSON = {
  "customers": [{
      "id": 100,
      "first": "Mike",
      "last": "Johnson",
      "email": "mjohnson@gmail.com",
      "position": "Consultant"
    },
    {
      "id": 101,
      "first": "John",
      "last": "Dunn",
      "email": "jdunn@gmail.com",
      "position": "Programmer"
    },
    {
      "id": 109,
      "first": "Lisa",
      "last": "Morgan",
      "email": "lmorgan@gmail.com",
      "position": "Secretary"
    },
    {
      "id": 233,
      "first": "Kris",
      "last": "Bradley",
      "email": "kbradley@gmail.com",
      "position": "Programmer"
    },
    {
      "id": 57,
      "first": "Dave",
      "last": "Hart",
      "email": "dhart@gmail.com",
      "position": "Supervisor"
    }
  ]
};

$(document).ready(function() {
  generateTbl();
});
var recordID = null;

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "<div class='table-responsive'><table class='table table-striped' id='customers'><thead><tr><th>Customer ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Position</th><th>Delete</th></thead><tbody>";

  for (var key in jsonData) {
    buildTbl += "<tr id='row_" + jsonData[key].id + "'><td data-id='id'>" + $.trim(jsonData[key].id) + "</td>";
    buildTbl += "<td data-id='first'>" + $.trim(jsonData[key].first) + "</td>";
    buildTbl += "<td data-id='last'>" + $.trim(jsonData[key].last) + "</td>";
    buildTbl += "<td data-id='email'>" + $.trim(jsonData[key].email) + "</td>";
    buildTbl += "<td data-id='position'>" + $.trim(jsonData[key].position) + "</td>";
    buildTbl += "<td class='text-center'><button type='button' class='btn btn-default btn-sm customer_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
  }
  buildTbl += "</tbody></table></div>";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', ':button.customer_delete', deleteCustomer);

function deleteCustomer() {
 recordID = $(this).closest('tr').attr('id'), // Get record ID.
    targetTr = $(this).parents('tr');
  $('#deleteModal').modal('show');  

}
  $('.confirm_delete').on('click', function() {
    if (recordID) {
      var table = $('#customers').DataTable(); // Select DataTable by ID.
      table.row(targetTr).remove().draw(); // Remove record from DataTable.
    }
  });
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Hearing Application</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <!-- *** Start: JS and CSS for DataTables. *** -->
  <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
  <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
  <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />
  <!-- *** End: JS and CSS for DataTables. *** -->
</head>

<body>
  <div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">Welcome to Main Page</div>
      <div class="panel-body">
        <div id="customers_data" class="table-responsive"></div>
      </div>
    </div>
  </div>
  <div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" 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">Confirm Delete</h4>
        </div>
        <div class="modal-body" id="delete_modalBody">
          <p>You are about to delete customer record, this procedure is irreversible.</p>
          <p>Do you want to proceed?</p>
          <p class="debug-url"></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default confirm_delete" data-dismiss="modal">Delete</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</body>

</html>
0 голосов
/ 09 мая 2018

Проблема в том, что вы связываете событие on click каждый раз, когда нажимаете удалить button. Это неправильно

Вот рабочий раствор

var myJSON = {
  "customers": [{
    "id": 100,
    "first": "Mike",
    "last": "Johnson",
    "email": "mjohnson@gmail.com",
    "position": "Consultant"
  }, {
    "id": 101,
    "first": "John",
    "last": "Dunn",
    "email": "jdunn@gmail.com",
    "position": "Programmer"
  }, {
    "id": 109,
    "first": "Lisa",
    "last": "Morgan",
    "email": "lmorgan@gmail.com",
    "position": "Secretary"
  }, {
    "id": 233,
    "first": "Kris",
    "last": "Bradley",
    "email": "kbradley@gmail.com",
    "position": "Programmer"
  }, {
    "id": 57,
    "first": "Dave",
    "last": "Hart",
    "email": "dhart@gmail.com",
    "position": "Supervisor"
  }]
};

$(document).ready(function() {
  generateTbl();
});

function generateTbl() {
  var jsonData = myJSON.customers,
    buildTbl = "<div class='table-responsive'><table class='table table-striped' id='customers'><thead><tr><th>Customer ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Position</th><th>Delete</th></thead><tbody>";

  for (var key in jsonData) {
    buildTbl += "<tr id='row_" + jsonData[key].id + "'><td data-id='id'>" + $.trim(jsonData[key].id) + "</td>";
    buildTbl += "<td data-id='first'>" + $.trim(jsonData[key].first) + "</td>";
    buildTbl += "<td data-id='last'>" + $.trim(jsonData[key].last) + "</td>";
    buildTbl += "<td data-id='email'>" + $.trim(jsonData[key].email) + "</td>";
    buildTbl += "<td data-id='position'>" + $.trim(jsonData[key].position) + "</td>";
    buildTbl += "<td class='text-center'><button type='button' class='btn btn-default btn-sm customer_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
  }
  buildTbl += "</tbody></table></div>";
  $('#customers_data').empty().append(buildTbl);
  buildDataTable('customers', [5], 5);
}

function buildDataTable(tblID, columnsArray, displayLength) {
  $('#' + tblID).DataTable({
    dom: 'Bfrtip',
    buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print'
    ],
    "iDisplayLength": displayLength,
    "aoColumnDefs": [{
      'bSortable': false,
      'aTargets': columnsArray
    }]
  });
}

$('#customers_data').on('click', ':button.customer_delete', deleteCustomer);

var recordID,
  targetTr;

function deleteCustomer() {
  recordID = $(this).closest('tr').attr('id'); // Get record ID.
  targetTr = $(this).parents('tr');

  $('#deleteModal').modal('show'); // Show delete modal box.

}

$('.confirm_delete').on('click', function() {
  if (recordID) {
    console.log('test');
    var table = $('#customers').DataTable(); // Select DataTable by ID.
    table.row(targetTr).remove().draw(); // Remove record from DataTable.
  }
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- *** Start: JS and CSS for DataTables. *** -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />


<div class="container">
  <div class="panel panel-primary">
    <div class="panel-heading">Welcome to Main Page</div>
    <div class="panel-body">
      <div id="customers_data" class="table-responsive"></div>
    </div>
  </div>
</div>
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" 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">Confirm Delete</h4>
      </div>
      <div class="modal-body" id="delete_modalBody">
        <p>You are about to delete customer record, this procedure is irreversible.</p>
        <p>Do you want to proceed?</p>
        <p class="debug-url"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default confirm_delete" data-dismiss="modal">Delete</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>
...