SOLVED

Re: CSS to target checkbox labels on forms

Go to solution
Nicholas_Manojl
Level 9

I know you can target the label individually, but is there a systematic method of targeting labels that appear next to checkboxes?

1 ACCEPTED SOLUTION
SanfordWhiteman
Level 10 - Community Moderator

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.).

View solution in original post

7 REPLIES 7
SanfordWhiteman
Level 10 - Community Moderator

Individual Checkbox fields, or checkboxes in a ​Checkboxes ​field?

Nicholas_Manojl
Level 9

Individual checkbox fields, as in a preference centre where each checkbox changes the value of a field directly.

SanfordWhiteman
Level 10 - Community Moderator

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.).

WolframLotz
Level 4

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

SanfordWhiteman
Level 10 - Community Moderator

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);     
  });

});

 

WolframLotz
Level 4

Hi @SanfordWhiteman 
thank you!

Nicholas_Manojl
Level 9

amazing, thanks again.