Fabian Sierra Fabian Sierra - 3 months ago 9
Javascript Question

Confirm function is not running properly

I have this function to send an array and then store it in the database, but I want to put a confirm message before to send it, It works but the problem is when I cancel the message, confirm button does not work more.

confirm.one('click', function() {
e.preventDefault();
if (window.confirm('Do you wish to continue?')) {
var data = "";
$("#tableConfirm tbody tr td input[type=checkbox]:checked").each(function() {
var result = [];
$(this).closest('tr').find('input[type="hidden"]').each(function() {
result.push($(this).val());
});
data = JSON.stringify(result);

$.ajax({
type: "POST",
url: getBaseUri() + '/payroll/createAll/',
data: {
datas: data
},
cache: false,
success: function(response) {
var table = $('#news');
var url = table.data('source');
clearFom();
$('#areac').val(null).trigger("change");
$('#conceptC').val(null).trigger("change");
$('#valueC').val('');
table.dataTable().fnReloadAjax(url);
$('#modalConfirm').modal('hide');
},
error: function(response) {
console.log(response);
}
});
});
} else {
return false;
}
});


I am sure that the problem is confirm.one() because only it lets me run the button once ,so when I click the confirm button again it does not longer works, but I need to avoid duplicate records, so I want to know if exists another way to do it or if when I cancel the message, the confirm button to run again.

Answer

You can just rebind one to the element on cancel.

function sendData(e) {
  e.preventDefault();
  if (window.confirm('Do you wish to continue?')) {
    var data = "";
    $("#tableConfirm tbody tr td input[type=checkbox]:checked").each(function() {
      var result = [];
      $(this).closest('tr').find('input[type="hidden"]').each(function() {
        result.push($(this).val());
      });
      data = JSON.stringify(result);

      $.ajax({
        type: "POST",
        url: getBaseUri() + '/payroll/createAll/',
        data: {
          datas: data
        },
        cache: false,
        success: function(response) {
          var table = $('#news');
          var url = table.data('source');
          clearFom();
          $('#areac').val(null).trigger("change");
          $('#conceptC').val(null).trigger("change");
          $('#valueC').val('');
          table.dataTable().fnReloadAjax(url);
          $('#modalConfirm').modal('hide');
        },
        error: function(response) {
          console.log(response);
        }
      });
    });
  } else {
    $(e.target).one('click', sendData);
  }
}


$('#confirm').one('click', sendData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="confirm">
  Confirm
</button>

Comments