2014-12-04 5 views
0

Я создал функцию, в которой я связываю событие beforeunload, и я вызываю его, когда страница загружается первой. Сначала, когда я нажимаю «Отменить», событие beforeunload снова срабатывает, и проверка не работает. Как это сделать?Подтвердить поля в «Отмена» Нажмите событие Onbeforeunload JQUERY

function closeOrRefreshPageEvents() { 
       // This submit event is used ONLY to run the validation when the user clicks "Cancel" to stay on the page 
       $("#formUpdateInstallations").submit(function (event) { 
        $.validate({ 
         form: '#formUpdateInstallations', 
         validateOnBlur: false, // disable validation when input looses focus 
         errorMessagePosition: 'top', 
         scrollToTopOnError: true, // Set this property to true if you have a long form 
         onError: function() { 
          alert('Validation failed'); 
         }, 
         onSuccess: function() { 
          alert('The form is valid!'); 
         } 
        }); 
        event.preventDefault(); 
       }); 

       $(window).bind('beforeunload', function() { 
        // Check if at least one Installation has been modified 
        var installationsChanged = false; 
        for (var z = 0; z < arrayOfInstallationsToUpdate.length; z++) { 
         if (arrayOfInstallationsToUpdate[z].modifiedRecord == "true") { 
          installationsChanged = true; 
          break; 
         } 
        } 
        // If any Installation has been changed then we warn the user, if he clicks "Cancel" then we submit the form only to run the Validation rules 
        if (installationsChanged) { 
         setTimeout(function() { 
          setTimeout(function() { 
           $("#formUpdateInstallations").submit(); 
          }, 1000); 
         }, 1); 

         return 'You will loose your changes if you continue!'; 
        } 
       }); 
      } 
+0

Вы можете бросить это в ручку или скрипку? Это поможет вам быстро получить помощь. – Todd

+0

Спасибо Тодд. Но я не думаю, что все логично вставить в мою скрипку:/ – Walloud

+0

Не беспокойтесь, мужик. Но серьезно не редкость писать целые сайты в кодеде. лол. https://stre.am - codepen -> возвышенный для вкладок вкладок -> repo – Todd

ответ

0

Фактически мне пришлось переместить блок проверки из обработчика события Submit в обработчик события onbeforeunload. ниже приведен правильный код:

function closeOrRefreshPageEvents() { 
      // This submit event is used ONLY to run the validation when the user clicks "Cancel" to stay on the page 
      $("#formUpdateInstallations").submit(function (event) { 
       event.preventDefault(); 
      }); 

      $(window).bind('beforeunload', function() { 
       // Validate fields when user clicks "Cancel" 
       $.validate({ 
        form: '#formUpdateInstallations', 
        validateOnBlur: false, // disable validation when input looses focus 
        errorMessagePosition: 'top', 
        scrollToTopOnError: true, // Set this property to true if you have a long form 
        onError: function() { 
         alert('Validation failed'); 
         window.onbeforeunload = function() { return false; }; 
         window.onbeforeunload = null; 
        }, 
        onSuccess: function() { 
         alert('The form is valid!'); 
         window.onbeforeunload = function() { return false; }; 
         window.onbeforeunload = null; 
        } 
       }); 

       // Check if at least one Installation has been modified 
       var installationsChanged = false; 
       for (var z = 0; z < arrayOfInstallationsToUpdate.length; z++) { 
        if (arrayOfInstallationsToUpdate[z].modifiedRecord == "true") { 
         installationsChanged = true; 
         break; 
        } 
       } 
       // If any Installation has been changed then we warn the user, if he clicks "Cancel" then we submit the form only to run the Validation rules 
       if (installationsChanged) { 
        setTimeout(function() { 
         setTimeout(function() { 
          window.onbeforeunload = function() { return false; }; 
          $("#formUpdateInstallations").submit(); 
         }, 500); 
        }, 1); 

        return 'You will loose your changes if you continue!'; 
       } 
      }); 
     } 
Смежные вопросы