Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

trigger('click') срабатывает дважды


Recommended Posts

Появилась интересная проблема. Я взял скрипт загрузки файла "из коробки" (версия 2.1). На локальном сервере всё рилииет как положено, но после усиновки на другой (реальный) сайт тот же версии появилась проблема, что при нажатии на кнопку (button type="button" id="button-upload"), после которой появляется форма для отправки файла и включается триггер на нажатие появившегося (input type="file"), дважды появляется диалоговое окно выпотому чтора файла. Первый раз после выпотому чтора файла, название его не фиксируется в (input type="file"), а второй раз уже фиксируется и срабатывает условие на появившееся значение в поле input и файл загружается. Кто может подсказать в чем может быть проблема?

Как решение подобных ситуаций предлагают использовать event.preventDefault() и event.stopPropagation(), но то ли я не ик/не им их применял, то ли проблема в чем-то другом.

Вот сам скрипт:

$(document).ready(function() {
  $('#button-upload').on('click', function() {
      $('#form-upload').remove();
      $('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');
      $('#form-upload input[name=\'file\']').trigger('click');
      if (typeof timer != 'undefined') {
          clearInterval(timer);
      }
      timer = setInterval(function() {
          if ($('#form-upload input[name=\'file\']').val() != '') {
              clearInterval(timer);
              $.ajax({
                  url: 'index.php?route=catalog/download/upload&token=<?php echo $token; ?>',
                  type: 'post',		
                  dataType: 'json',
                  data: new FormData($('#form-upload')[0]),
                  cache: false,
                  contentType: false,
                  processData: false,		
                  beforeSend: function() {
                      $('#button-upload').button('loading');
                  },
                  complete: function() {
                      $('#button-upload').button('reset');
                  },	
                  success: function(json) {
                      if (json['error']) {
                          alert(json['error']);
                      }
                      if (json['success']) {
                          alert(json['success']);
                      }
                  },			
                  error: function(xhr, ajaxOptions, thrownError) {
                      alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                  }
              });
          }
      }, 500);
  });
});

 

Link to comment
Share on other sites


1 час назад, Prooksius сказал:

может на страниэто есть две икие формы, два иких input type="file", поэтому оба и открываются.

икая форма только одна, есть еещё <form class="form-horizontal">, но эи повлиять не могла, еещё есть  <input type="checkbox>, а икже несколько textarea, но никаких совпагдений по названиям нет.

1 час назад, Prooksius сказал:

посмотрите, есть ли в консоли ошибки какие..

смотрел, им пусто

Link to comment
Share on other sites


3 часа назад, stasonsky сказал:

#button-upload

лучше поменять на что-то свое, уникальное.

3 часа назад, stasonsky сказал:

#form-upload

тоже.

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.