Kieron606 Kieron606 - 6 months ago 25
Javascript Question

jQuery event listeners firing multiple times

I'm having an issue with jQuery, when I re-open my modal a few times any event listeners in the modal will fire a few times too? I have a implemented an example showing the problem.

For example if you open and close the modal 5 times, the event will run 5 times.



$(document).ready(function() {

$(".testButton").click(function(event) {
event.preventDefault(); // cancel default behavior

$('.validation-list-modal').modal('show');

var ruleID = $('#mongoid').val();

$('.validation-list-modal').on('shown.bs.modal', function(e) {
alert('test');
})

document.getElementById("uploadButtonEdit").addEventListener("click", function() {
document.getElementById("csvListEdit").click();
});

$('form#csvUploadEdit').submit(function(event) {
event.preventDefault();

$('.selectedFileName').hide();
var ruleID = $('#mongoid').val();
var importCount = 0;
var notImportedCount = 0;
var formData = new FormData(this);
formData.append('ruleID', ruleID);

$.ajax({
url: '/ajax/fileUpload.php',
type: 'POST',
dataType: 'JSON',
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
})
.done(function(data) {
$.each(data, function(index, val) {
if ($('.validValuesList ul li:contains(' + val + ')').length) {
notImportedCount++;
} else {
importCount++;
$('.validValuesList ul').append('<span class="deleteValidEdit" title="Delete Autofix">X</span><li class="validTag">' + val + '</li>');
}
});
if (importCount == 0) {
$('.alert-modal').modal('show');
$('.alert-modal .modal-dialog').removeClass('modal-wide');
$('.alert-modal .modal-dialog').removeClass('modal-lg');
$('.alertMessage').text("");
$('.additionalAlertMessage').text("");
$('.alertMessage').text(notImportedCount + ' duplicates were not imported');
} else if (notImportedCount == 0) {
$('.alert-modal').modal('show');
$('.alert-modal .modal-dialog').removeClass('modal-wide');
$('.alert-modal .modal-dialog').removeClass('modal-lg');
$('.alertMessage').text("");
$('.additionalAlertMessage').text("");
$('.alertMessage').text(importCount + ' new values succesfully imported');
} else {
$('.alert-modal').modal('show');
$('.alert-modal .modal-dialog').removeClass('modal-wide');
$('.alert-modal .modal-dialog').removeClass('modal-lg');
$('.alertMessage').text("");
$('.additionalAlertMessage').text("");
$('.alertMessage').text(importCount + ' new values succesfully imported');
$('.additionalAlertMessage').text(notImportedCount + ' duplicates were not imported');
}
})
.fail(function(data) {
$('.alert-modal').modal('show');
$('.alert-modal .modal-dialog').removeClass('modal-wide');
$('.alert-modal .modal-dialog').removeClass('modal-lg');
$('.alertMessage').text("");
$('.additionalAlertMessage').text("");
$('.alertMessage').text("You have selected an incorrect file type. Please select a CSV.")
})
});
})
});

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



<!-- Modal where you will be able to add new rule -->
<div class="modal fade validation-list-modal" tabindex="-1" role="dialog" aria-labelledby="LargeModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">

<div class="modal-dialog modal-wide">

<div class="modal-content">

<div class="modal-header modal-header-custom">
<input class="ruleID" type="hidden"></input>
<button type="button" class="close destroyTable clearValidModals" data-dismiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title">Validation List</h4>
</div>

<div class="modal-body">
<div class="autofixesSection">
<div style="float: left; width: 190px; ">
<form method="post" action="fileUpload.php" enctype="multipart/form-data" id="csvUploadEdit">
<input type="file" name="csvList" id="csvListEdit">

</form>
</div>
<div style="float: left; width: 76% !important; max-width: 76%; max-height: 50%; margin-left: 65px;">
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default clearValidModals" data-dismiss="modal">Close</button>
</div>

</div>

</div>

</div>



<button class="testButton btn btn-primary">open modal</button>




Answer

$(document).ready(function() {
    $('.validation-list-modal').on('shown.bs.modal', function(e) {
      alert('test');
    })
  $('#upload').click(function(event) {
      alert('upload');
      event.preventDefault();

      $('.selectedFileName').hide();
      var ruleID = $('#mongoid').val();
      var importCount = 0;
      var notImportedCount = 0;
      var formData = new FormData(this);
      formData.append('ruleID', ruleID);

      $.ajax({
          url: '/ajax/fileUpload.php',
          type: 'POST',
          dataType: 'JSON',
          data: formData,
          contentType: false, // The content type used when sending data to the server.
          cache: false, // To unable request pages to be cached
          processData: false, // To send DOMDocument or non processed data file it is set to false              
        })
        .done(function(data) {
          $.each(data, function(index, val) {
            if ($('.validValuesList ul li:contains(' + val + ')').length) {
              notImportedCount++;
            } else {
              importCount++;
              $('.validValuesList ul').append('<span class="deleteValidEdit" title="Delete Autofix">X</span><li class="validTag">' + val + '</li>');
            }
          });
          if (importCount == 0) {
            $('.alert-modal').modal('show');
            $('.alert-modal .modal-dialog').removeClass('modal-wide');
            $('.alert-modal .modal-dialog').removeClass('modal-lg');
            $('.alertMessage').text("");
            $('.additionalAlertMessage').text("");
            $('.alertMessage').text(notImportedCount + ' duplicates were not imported');
          } else if (notImportedCount == 0) {
            $('.alert-modal').modal('show');
            $('.alert-modal .modal-dialog').removeClass('modal-wide');
            $('.alert-modal .modal-dialog').removeClass('modal-lg');
            $('.alertMessage').text("");
            $('.additionalAlertMessage').text("");
            $('.alertMessage').text(importCount + ' new values succesfully imported');
          } else {
            $('.alert-modal').modal('show');
            $('.alert-modal .modal-dialog').removeClass('modal-wide');
            $('.alert-modal .modal-dialog').removeClass('modal-lg');
            $('.alertMessage').text("");
            $('.additionalAlertMessage').text("");
            $('.alertMessage').text(importCount + ' new values succesfully imported');
            $('.additionalAlertMessage').text(notImportedCount + ' duplicates were not imported');
          }
        })
        .fail(function(data) {
          $('.alert-modal').modal('show');
          $('.alert-modal .modal-dialog').removeClass('modal-wide');
          $('.alert-modal .modal-dialog').removeClass('modal-lg');
          $('.alertMessage').text("");
          $('.additionalAlertMessage').text("");
          $('.alertMessage').text("You have selected an incorrect file type. Please select a CSV.")
        })
  });
  $(".testButton").click(function(event) {
    event.preventDefault(); // cancel default behavior

    $('.validation-list-modal').modal('show');

    var ruleID = $('#mongoid').val();

    //document.getElementById("uploadButtonEdit").addEventListener("click", function() {
      //document.getElementById("csvListEdit").click();
    //});


  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />



<!-- Modal where you will be able to add new rule -->
<div class="modal fade validation-list-modal" tabindex="-1" role="dialog" aria-labelledby="LargeModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">

  <div class="modal-dialog modal-wide">

    <div class="modal-content">

      <div class="modal-header modal-header-custom">
        <input class="ruleID" type="hidden"></input>
        <button type="button" class="close destroyTable clearValidModals" data-dismiss="modal" aria-hidden="true">x</button>
        <h4 class="modal-title">Validation List</h4>
      </div>

      <div class="modal-body">
        <div class="autofixesSection">
          <div style="float: left; width: 190px; ">
            <form method="post" action="fileUpload.php" enctype="multipart/form-data" id="csvUploadEdit">
              <input type="file" name="csvList" id="csvListEdit">

            </form>
          </div>
          <div style="float: left; width: 76% !important; max-width: 76%; max-height: 50%; margin-left: 65px;">
          </div>
          <div class="clearfix"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default btn-primary clearValidModals" id="upload">Upload</button> 
        <button type="button" class="btn btn-default clearValidModals" data-dismiss="modal">Close</button>
      </div>

    </div>

  </div>

</div>



<button class="testButton btn btn-primary">open modal</button>

you have to put 'shown.bs.modal' event outside click event handler

UPDATE

In your code, there are problems.

  1. ID of uploadButtonEdit doesn't exist in HTML
  2. I don't know why you use submit event handler. I think you want to ajax request when click submit button. But In HTML, doesn't exist submit button.

So, I create upload button and click event listener. you can ajax request in click event listener

Comments