SOLVED

How to add a global form multiple forms on the same page

Go to solution
SanfordWhiteman
Level 10 - Community Moderator

Re: How to add a global form multiple forms on the same page

There’s no reason to consider the Render event at all from what I can see. Everything you need is there upon Ready.

hlassis
Level 2

Re: How to add a global form multiple forms on the same page

Got it. So, here's a working solution:
HTML:

 

<form class="mktoForm" data-formId="X005" data-formInstance="one"></form>
<form class="mktoForm" data-formId="x005" data-formInstance="two"></form>

 

 

JS:

 

(function() {
	/* config area - replace with your instance values */

	var formIds = [X005],
		podId = '//info.example.com',
		munchkinId = '690-TWA-183';

	/* no need to touch anything below this line */

	var MKTOFORM_ID_PREFIX = 'mktoForm_', MKTOFORM_ID_ATTRNAME = 'data-formId';

	formIds.forEach(function(formId) {
		var loadForm = MktoForms2.loadForm.bind(
			MktoForms2,
			podId,
			munchkinId,
			formId
		),
			formEls = [].slice.call(
				document.querySelectorAll('[' + MKTOFORM_ID_ATTRNAME + '="' + formId + '"]')
			);

		(function loadFormCb(formEls) {
			var formEl = formEls.shift();
			formEl.id = MKTOFORM_ID_PREFIX + formId;

			loadForm(function(form) {
				formEl.id = '';
				formEls.length && loadFormCb(formEls);
			});
		})(formEls);
	});
})();

MktoForms2.whenReady(function(readyForm){
	var form = readyForm.getFormElem()[0];
	var instance = form.dataset.forminstance;
	/* Follow-up URLs */
			// Add an IF/ELSE IF to each copy of the form and then change the location.href inside to change to where each copy needs to go after submitted
	readyForm.onSuccess(function(submittedValues, followUpUrl){
		if (instance == "one") {
			location.href = "https://www.bing.com";
		} else if (instance == "two" ) {
			location.href = "https://www.google.com";
		}
		return false;
	});
	/* CTA Texts */
		// querySelectorAll generates a NodeList. Copy a line to each copy of the form you have on the page, counting from zero
			document.querySelectorAll('.mktoButton')[0].innerText = 'Watch Webinar 1'; 
			document.querySelectorAll('.mktoButton')[1].innerText = 'Watch Webinar 2'; 
});

 


I know it can be better (and if anyone else finds a way to improve please post here) but it works! Thanks, @SanfordWhiteman for your help, I learned a lot working on this.

P.S: Remember that the forms2.min.js script is been loaded outside this on my case.

SanfordWhiteman
Level 10 - Community Moderator

Re: How to add a global form multiple forms on the same page

Nice! Yes, that’s one way to switch based on the instance. I wouldn’t use dataset, though. getAttribute() is more direct as it uses the data- attribute name exactly as-is.

 

Also not too fond of the separation of the button text(s) and the destination URL(s). That data should be combined into one centrally managed config object.