javascriptjqueryhtmlcheckboxdropdownbox

How to Hide Value Based On CheckBox include Required when Checked (Drop-down box version included)


I wish to display the text areas when the checkbox is checked and hide them when it is not. The Interface can be run but the checkbox is not clickable.

$(document).ready(function() {
  $('#ifbroken').change(function() {
    if (this.checked)
      $('#dvchk').fadeIn('slow');
    else
      $('#dvchk').fadeOut('slow');
  })
});
#dvchk {
  display: none
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
</script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="input-field col s12">
  <input type="checkbox" id="ifbroken">
  <label for="ifborken">If Broken</label>
</div>

<div class="input-field col s12" id="dvchk">
  <label for="Problem">Problem</label></br>
  </br>
  <textarea name="Problem" style="width:600px; height:200px;"></textarea>
</div>

<div class="input-field col s12" id="dvchk">
  <label for="ActionTaken">Action Taken</label></br>
  </br>
  <textarea name="ActionTaken" style="width:600px; height:200px;"></textarea>
</div>

<div class="input-field col s12" id="dvchk">
  <label for="BuyOff">Buy Off</label></br>
  </br>
  <textarea name="BuyOff" style="width:600px; height:200px;"></textarea>
</div>


Solution

  • You have multiple identical IDs and invalid HTML and too many jQuery files loaded

    This works

    I changed the IDs to class, fixed the typo in the label and the invalid </br>

    I also moved the inline style into the stylesheet

    function toggleField() {
      $fld = $(".dvchk").find(":input").prop("required", this.checked);
    
      if (this.checked) $('.dvchk').fadeIn('slow'); // there is alas no fadeToggle(boolean)
      else $('.dvchk').fadeOut('slow');
    }
    $(function() {
      $('#ifbroken').on("click", toggleField)
    });
    .dvchk {
      display: none
    }
    
    textarea {
      width: 600px;
      height: 200px;
    }
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <form>
      <div class="input-field col s12">
        <input type="checkbox" id="ifbroken">
        <label for="ifbroken">If Broken</label>
      </div>
    
      <div class="input-field col s12 dvchk">
        <label for="Problem">Problem</label><br /><br />
        <textarea name="Problem"></textarea>
      </div>
    
      <div class="input-field col s12 dvchk">
        <label for="ActionTaken">Action Taken</label><br /><br />
        <textarea name="ActionTaken"></textarea>
      </div>
    
      <div class="input-field col s12 dvchk">
        <label for="BuyOff">Buy Off</label><br /><br />
        <textarea name="BuyOff"></textarea>
      </div>
      <input class="dvchk" type="submit" />
    </form>