Search code examples
javascripthtmlcheckboxdisabled-input

Toggle enabled&disabled all inputs in div when chceckbox clicked


I am trying to remove the attribute disabled at each input when the chceckbox is clicked. I was able to turn these inputs on but I have a problem with switching them back off.

     <div class='single-service-<?php echo $row["id"]; ?>'>
      <input type='checkbox'>
      <label><?php printf ("%s", $row["service_name"]); ?></label>
      <label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
      <label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
    </div>


    var checkboxes = document.querySelectorAll("input[type='checkbox']");

    for(var i=0; i < checkboxes.length; i++) {
      checkboxes[i].addEventListener('click', function() {
        var div = this.parentNode;
        var x = div.childNodes;
        for(y=0; y < x.length; y++) {
          x[y].disabled = false;
        }
      }, false);
    }

Solution

  • You should substitude x[y].disabled = false; with

    if(x[y].type === "number") x[y].disabled = !x[y].disabled;

    or if you want to disable all inputs, including your checkbox just use x[y].disabled = !x[y].disabled;.