I know you can target the label individually, but is there a systematic method of targeting labels that appear next to checkboxes?
Solved! Go to Solution.
MktoForms2.whenReady(function(form){
var formEl = form.getFormElem()[0],
labels = formEl.querySelectorAll('label.mktoLabel');
[].slice.call(labels)
.forEach(function(label){
label.className += ' label-' + formEl.querySelector('#' + label.htmlFor).type;
});
});
This'll add an additional class to every <label> element that corresponds to its target element's type (class="label-checkbox", class="label-email", etc.).
Individual Checkbox fields, or checkboxes in a Checkboxes field?
Individual checkbox fields, as in a preference centre where each checkbox changes the value of a field directly.
MktoForms2.whenReady(function(form){
var formEl = form.getFormElem()[0],
labels = formEl.querySelectorAll('label.mktoLabel');
[].slice.call(labels)
.forEach(function(label){
label.className += ' label-' + formEl.querySelector('#' + label.htmlFor).type;
});
});
This'll add an additional class to every <label> element that corresponds to its target element's type (class="label-checkbox", class="label-email", etc.).
amazing, thanks again.
Hi Sanford
this solution is really amazing. It works wonderful for forms which where loaded instantly. Only issue I have is that in case you have a dynamic form, e. g. some checkboxe/labels appear just due to interaction with the form, "whenReady" does not seem to catch this changes.
Is there a trigger which can be used to run the code again after a dynamic change?
Kind regards
Wolfram
That code is pretty suboptimal at this point. Replace it with this, which will not only pick up dynamic elements (e.g. Visibility Rules) but also correct some edge cases:
MktoForms2.whenRendered(function(mktoForm){
const arrayify = getSelection.call.bind([].slice);
let formEl = mktoForm.getFormElem()[0],
labels = formEl.querySelectorAll("label:not([data-for-type])");
arrayify(labels)
.forEach(function(label){
let relatedInput = formEl.querySelector("#" + label.htmlFor) || formEl.querySelector("[name='" + label.htmlFor + "']") || { type : "" };
label.setAttribute("data-for-type", relatedInput.type);
});
});