MktoForms2 :: Iterate and resend form

by sanford

HTML

<script src="//app-sj01.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_501"></form>

JavaScript

MktoForms2.loadForm("//app-sj01.marketo.com", "410-XOR-673", 501);
MktoForms2.whenReady(function(form) {

  var formEl = form.getFormElem()[0],
  emailEl = formEl.querySelector('#Email'),
	referrals = [].slice.call(formEl.querySelectorAll('INPUT[name="referral"]'));

  form.addHiddenFields({
    '_mkt_trk': ''
  });

  form.onSubmit(function(form) {
    form.onSubmit();
    form.setValues({
      '_mkt_trk': ''
    });
    
    

		// hide the original #Email 'cuz it looks weird to see it being repopulated
		var masterEmail = emailEl.cloneNode();
    emailEl.parentNode.appendChild(masterEmail);
    formEl.querySelector('LABEL[for="Email"]').textContent = "Processing";
    
	
    // only pass the inputs with a value
    var filledReferrals = referrals.filter(function(el) {
      return !!el.value;
    });

    // iterate over the referrals and repost the form for each one
    filledReferrals.forEach(function(itm, idx) {      
      form.onSuccess(function(vals, tyURL) {
        // void the onSuccess to avoid an infinite loop, but continue on the last one
        if ( idx < filledReferrals.length - 1 || filledReferrals.length == 1 ) {
          form.onSuccess();
        } else {
          form.onSuccess(function(vals, tyURL) {
          });
        }

        form.setValues({
          'Email': itm.value
        });
        
        itm.parentNode.replaceChild(emailEl,itm)
        
        form.submit();

        return false;
      });
    });
  });
});