placeholder text in form breaks when add radio buttons

324 Views Asked by At

I have used the below script to use placeholders but when I add radio buttons the script breaks. What is missing?

var labels = document.querySelectorAll("label");
var i = labels.length;
while (i--) {
  var label = labels.item(i);
  var text = label.textContent;
  label.parentNode.classList.contains("required") && (text += " *");
  var nextElement = label.nextElementSibling;

  if (nextElement.tagName == 'SELECT') {
    nextElement.options[0].text = text;
   } else {
    nextElement.setAttribute("placeholder", text);
   }
  label.parentNode.removeChild(label);
}
var elements = document.querySelectorAll('.errors, .no-label');
Array.prototype.forEach.call(elements, function(el, i) {
  el.parentNode.removeChild(el);
});

Here is the jsfiddle: https://jsfiddle.net/katyhege/zdqLtmsn/

2

There are 2 best solutions below

2
On BEST ANSWER

It seems that when script breaks it shows nextElement undefined, so you can have check for this. Try this once if it works for you,

var labels = document.querySelectorAll("label");
    var i = labels.length;
    while (i--) {
    var label = labels.item(i);
    var text = label.textContent;
    label.parentNode.classList.contains("required") && (text += " *");
    var nextElement = label.nextElementSibling;

      // This is what I changed:
     if(nextElement){
       if (nextElement.tagName == 'SELECT') {
        nextElement.options[0].text = text;
       } else {
        nextElement.setAttribute("placeholder", text);
       }
     label.parentNode.removeChild(label);
     }
  }
var elements = document.querySelectorAll('.errors, .no-label');
Array.prototype.forEach.call(elements, function(el, i) {
el.parentNode.removeChild(el);
});

Or you can do one more solution, Just replace

var i = labels.length;

with

var i = labels.length-2;

Also you can make it work properly by changing in your HTML, Which cause the problem basically, You can see for your last two labels(used for radio buttons), you did not put your inputs (radio buttons) next to label but you put them before labels, So it can not find the next sibling there. If you will write your radio inputs next to label (as u did for other inputs) then it will work properly. Thanks.

Best of luck :)

0
On

to leave the labels for the radio/checkbox fields I used:

var labels = document.querySelectorAll("p.pd-text label, p.pd-select label, p.pd-textarea label");