简体   繁体   中英

Unhide div using jQuery

Im trying to show this div when the user select Etudiant in selectbox

<div class="form-group">
  <label for="">Type du compte</label>
  <select id="type" required class="chosen form-control" name="type"  >
    <option required selected disabled value="fail">Choix type du compte </option>    
    <option required  value="professeur">Professeur </option>    
    <option required  value="etudiant">Etudiant </option>    
  </select>
</div>

<div id="phone" hidden class="form-group">
  <label for="">Téléphone</label>
  <input  required class="form-control"  name="phone" class="form-control">
</div>

I already tried this using jQuery unsuccessfully

<script>
  $(document).ready(function () {
    $("#type").change(function () {
      switch($(this).val()) {      
        case 'etudiant':
          $("#phone").show();
          break;
        default:
          $("#phone").hide();
      } 
    });
  });
</script>

You can accomplish this behavior by adding an EventListener to the select element & checking if the selected option 's value is equal to etudiant & if the display property is set to none like so:

let selectElement = document.getElementById('type')

const phoneDiv = document.querySelector('#phone');

selectElement.addEventListener('change', (e) => {
  if (e.target.value === 'etudiant' && phoneDiv.style.display === '') {
    phoneDiv.style.display = 'block'
  } else {
    phoneDiv.style.display = ''
  }
})

You can check this live code sample .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM