Отправка нескольких форм - JavaScript вопросов - PullRequest
0 голосов
/ 08 мая 2020

Здравствуйте, мне нужна помощь в проверке кода JavaScript, который, похоже, у нас есть много слушателей onValidate, которые не взаимодействуют друг с другом в коде JavaScript при отправке формы. Мне посоветовали при использовании стека из нескольких onValidates, нам нужно тщательно кодировать, чтобы form.submittable () (например) переносился от события к событию и в предсказуемом порядке. Они не могут работать полностью независимо прямо сейчас, поэтому интересно, может ли кто-нибудь дать совет:

 <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    
<!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script>
/*
 * @author Sanford Whiteman
 * @version v1.104
 * @license MIT License: This license must appear with all reproductions of this software.
 *
 * Create a completely barebones, user-styles-only Marketo form
 * by removing inline STYLE attributes and disabling STYLE and LINK elements
 */
function destyleMktoForm(mktoForm, moreStyles){
    var formEl = mktoForm.getFormElem()[0],
        arrayFrom = Function.prototype.call.bind(Array.prototype.slice);

    // remove element styles from <form> and children
    var styledEls = arrayFrom(formEl.querySelectorAll("[style]")).concat(formEl);   
    styledEls.forEach(function(el) {
        el.removeAttribute("style");
    });

    // disable remote stylesheets and local <style>s
    var styleSheets = arrayFrom(document.styleSheets);  
    styleSheets.forEach(function(ss) {
        if ( [mktoForms2BaseStyle,mktoForms2ThemeStyle].indexOf(ss.ownerNode) != -1 || formEl.contains(ss.ownerNode) ) {
            ss.disabled = true;
        }
    });
         
   if(!moreStyles) {
      formEl.setAttribute("data-styles-ready", "true");
   }
};

MktoForms2.whenRendered(function(form) {
  destyleMktoForm(form);
});
</script>
    

<script type="text/javascript">
        MktoForms2.whenReady(function(mktoForm) {
        var userConfig = {
        apiKeys : {
        recaptcha : "6Lcgd8cUAAAAAMjh5gfs66xMJqfQrGf6IEnD1xyO"
        },
        fields : {
        recaptchaFinger : "lastReCAPTCHAUserFingerprint"
        },
        actions : {
        formSubmit : "form"
        }
        };
        /* --- NO NEED TO TOUCH BELOW THIS LINE --- */
        var formEl = mktoForm.getFormElem()[0],
        submitButtonEl = formEl.querySelector("button[type='submit']"),
        recaptchaLib = document.createElement("script");
        /* pending widget ready */
        submitButtonEl.disabled = true;
        /* pending verify */
        mktoForm.submittable(false);
        mktoForm.locked = false;
        var recaptchaListeners = {
        ready : function() {
        submitButtonEl.disabled = false;
        }
        };
        Object.keys(recaptchaListeners).forEach(function globalize(fnName){
        window["grecaptchaListeners_" + fnName] = recaptchaListeners[fnName];
        });
        mktoForm.onValidate(function(native) {
        if (!native) return;
        grecaptcha.ready(function() {
        grecaptcha.execute(userConfig.apiKeys.recaptcha, {
        action: userConfig.actions.formSubmit
        })
        .then(function(recaptchaFinger) {
        var mktoFields = {};
        if (mktoForm.locked == false) {
        console.log("primary recaptcha response resolved");
        mktoForm.locked = true;
        mktoFields[userConfig.fields.recaptchaFinger] = recaptchaFinger;
        mktoForm.addHiddenFields(mktoFields);
        mktoForm.submittable(true);
        mktoForm.submit();
        } else {
        console.log("secondary recaptcha response resolved");
        }
        });
        });
        });
        /* inject the reCAPTCHA library */
        recaptchaLib.src = "https://www.google.com/recaptcha/api.js?render=" + userConfig.apiKeys.recaptcha + "&onload=grecaptchaListeners_ready";
        document.head.appendChild(recaptchaLib);
        });



    
</script>    
 <!-- Javascript for Blocking Free Email Domains - North America -->
      <script>
    // to make fancy buttons.  Uses noConflict just in case
     var $jQ = jQuery.noConflict();

     // Use jQuery via $j(...)
     $jQ(document).ready(function(){

       /*$jQ('input[id=mktFrmSubmit]').wrap("<div class='buttonSubmit'></div>");
       $jQ(".buttonSubmit").prepend("<span></span>");*/

     });
   </script>

<script>
var userOptions = {   basePath: "/rs/838-LDP-483/images/"  };  var lists = [   {     name: "disposable",     file: "disposable.txt",     error: "Must be a business email."   },   {     name: "free",     file: "disposable.txt",     error: "Must be a business email."   } ];  /* --- No need to edit below this line! --- */  lists.forEach(function(list) {   var listObj = document.createElement("object");    listObj.type = "text/plain";   listObj.data = userOptions.basePath + list.file;   listObj.onload = function(e) {     list.RE = new RegExp(       "@(" +         this.contentDocument.documentElement.textContent           .split("\n")           .join("|")           .replace(".", "\\.") +         ")$"     );   };   document.body.appendChild(listObj); });  MktoForms2.whenReady(function(form) {   var emailJQ = form.getFormElem().find("#Email");    form.onValidate(function(nativeValid) {     if (!nativeValid) return;      var email = form.getValues().Email,         firstError;          if (lists.some(function(list) {         if (list.RE && list.RE.test(email)) {           firstError = list.error;           return true;         }       })) {       form.submittable(false);       form.showErrorMessage(firstError, emailJQ);     } else {       form.submittable(true);     }   }); });
</script>
  <!-- End Javascript for Blocking Free Email Domains - North America  -->
 <script>
/* moving to top
    var email1;
    var email2;
    MktoForms2.whenReady(function (mktoForm) {
        var checkIfEmailsMatch = function (even) {
            // No need to validate if one of the input is empty
            if(email1.value != "" && email2.value != "") {
                // Emails do not match
                if(email1.value != email2.value) {
                    var confirmEmailElement = form.getFormElem().find("#emailAddressConfirm");
					form.getFormElem().find("#emailAddressConfirm").css({"border": "2px solid red"});
                    form.showErrorMessage("Email addresses must match.", confirmEmailElement );
                    form.submittable(false);
                }
                else {
                  email2.style.border = "";
                  form.submittable(true);
                }
            }
        }
        email1 = document.getElementById("Email");
        email2 = document.getElementById("emailAddressConfirm");
        // Add to the email and the confirmation an event that start when the user
        // exit one of the two input
        if(email2 != null) {
            email1.addEventListener("blur", checkIfEmailsMatch);
            email2.addEventListener("blur", checkIfEmailsMatch);
            form.onValidate(function()
            {
                var vals = form.vals();
                if (vals.Email == vals.emailAddressConfirm)
                {
                    form.submittable(true);
                } else
                {
                    var confirmEmailElement = form.getFormElem().find("#emailAddressConfirm");
                    form.showErrorMessage("Email addresses must match.", confirmEmailElement );
                    form.submittable(false);
                }
            });
        }
    });
*/    
</script>
<script>
/* put right inside closing body, inside script tags 
MktoForms2.whenReady(function(mktoForm) {
});
//moving up
*/
</script> 
<script type="text/javascript" src="//munchkin.marketo.net//munchkin.js"></script><script>Munchkin.init('838-LDP-483', {customName: 'reCAPTCHA-V3_recaptchatestpage2', wsInfo: 'j1RR'});</script> 
<script type="text/javascript" src="/js/stripmkttok.js"></script></body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...