Brayn Brayn - 20 days ago 6
HTML Question

Input field appearing on default checked select box

I'm working on a form where we have the option to assign products to an object or in this case an user. Depending on the values given in our database that is retrieved and used in the code this user may have one of these specific product by default.

if($Pants=="1"){
echo "<input type='checkbox' onclick='PantsInput(this);' checked>Pants<br>";
}
else {
echo "<input type='checkbox'> Pants<br>";
}


There's a little JavaScript that creates a text input field if the checkbox is selected. It works, but ONLY if I go ahead and select it manually.

What I am trying to accomplish is for the script to recognize if the checkbox is already checked or not. It should still be possible to do it manually, but it would be great for the fields to appear on load if the checkbox is already checked.

Here's the script:

function PantsInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
input.value = "1";
input.name = "AmountPants"
var div = document.createElement("div");
div.id = cbox.name;
div.innerHTML = "Amount of pants: ";
div.appendChild(input);
document.getElementById("pantsinput").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}


Here's a JSFiddle that shows what I am struggling with:
https://jsfiddle.net/orqweyzc/

The box is already checked but the field will only appear if you go ahead and uncheck and check it again yourself. I've tried some different DOM Events, but can't seem to do it.

Answer

You could something like this

window.addEventListener('load', function() {
  var inputs = document.querySelectorAll('input');
  
  for (var i = 0; i < inputs.length; i++) {
    
    switch (inputs[i].getAttribute("data-type")) {
        
      case 'pants':      
      case 'shirts':
        inputs[i].addEventListener('click', function(e) {
          if (e.target.checked) {
            addElement(e.target);
          } else {
            document.getElementById(e.target.name).remove();
          }
        })
        
        if (inputs[i].checked) {
          addElement(inputs[i]);
        }
        break;
        
    }
  }
})

function addElement(t) {
  var vals = t.getAttribute('data-text').split('|');
  var input = document.createElement("input");
  input.type = "text";
  input.value = vals[0];
  input.name = vals[1];
  var div = document.createElement("div");
  div.id = t.name;
  div.innerHTML = vals[2];
  div.appendChild(input);
  document.getElementById(vals[3]).appendChild(div);
}
<p>Clothing</p>
<input type="checkbox" name="check1" checked data-type="pants" 
       data-text="1|AmountPants|Amount of pants: |pantsinput" />Pants
<br>
<input type="checkbox" name="check2" data-type="shirts" 
       data-text="2|AmountShirts|Amount of shirts: |shirtinput" />Shirt
<br>

<p id="pantsinput"></p>
<p id="shirtinput"></p>

Comments