Because the markup is not loaded into the DOM on page load, as you have found, you can't bind events or trigger parts of your script to load when the next page of your form is loaded.
The only way we have found to do this is by using a MutationObserver
on the .sitecore-form
element. This will fire off an event when the new markup is loaded into the DOM and you can then work with the markup for that page.
We usually create this script as part of a base theme or in the sites theme scripts for an SXA site. For non-SXA sites, this can just be a script in your site.
In the examples below the updateForm
function is called when new pages are loaded and you can write any code you need to modify the DOM in there.
Examples:
XA.component.forms = (function ($) {
"use strict";
var api = {};
api.init = function () {
$(function () {
api.initializeForms();
});
};
api.initializeForms = function() {
var target = document.querySelector('.sitecore-form');
var observer = new MutationObserver(function(mutations) {
var hasMutations = false;
for (var index = 0; index < 1; index++) {
var mutation = mutations[index];
if (mutation.type === 'childList' && mutation.addedNodes.length) {
hasMutations = true;
break;
}
}
if (hasMutations) {
api.updateForm();
}
});
if (target) {
observer.observe(target, {
childList: true,
attributes: true,
characterData:true,
subtree: true
});
}
api.updateForm();
};
api.updateForm = function () {
// TODO: Add your code here to initialise/bind events etc... to each page
// in the multipage form
// Example, add a css class to all labels of required fields:
$(".sitecore-form input[data-val-required]").prev("label").addClass("required");
};
return api;
}(jQuery));
XA.register("forms", XA.component.forms);
The above is an SXA script file.
For non-SXA something like this should work:
$(function() {
var target = document.querySelector('.sitecore-form');
var observer = new MutationObserver(function(mutations) {
var hasMutations = false;
for (var index = 0; index < 1; index++) {
var mutation = mutations[index];
if (mutation.type === 'childList' && mutation.addedNodes.length) {
hasMutations = true;
break;
}
}
if (hasMutations) {
api.updateForm();
}
});
if (target) {
observer.observe(target, {
childList: true,
attributes: true,
characterData:true,
subtree: true
});
}
updateForm();
});
const updateForm = function () {
// TODO: Add your code here to initialise/bind events etc... to each page
// in the multipage form
// Example, add a css class to all labels of required fields:
$(".sitecore-form input[data-val-required]").prev("label").addClass("required");
};