Ad

Dynamicly Apply Css Changes On Html Code With Js

- 1 answer

here's the situation

I have a select element in my html code, with many option. One of these options is "Other". What I want is, when I select "Other", without refreshing the page, display an input element right under the select one with JS. The problem is that I have to refresh the page to see the change. Can you help me? :)

There's my code :

<label for="select-tribunal" class="form-label">Cadre Légal</label>
            <select id="select-tribunal" required class="form-select" aria-label="Default select example">
                <?php
                foreach ($tribunaux as $tribunal){
                    echo '<option value="'.$tribunal['id'].'">'.$tribunal['nom'].'</option>';
                }
                ?>
                <option value="0">Autre Tribunal</option>
            </select>
                <input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">
            <script>
                var tribunal = document.getElementById("select-tribunal");
                    if (tribunal.options[tribunal.selectedIndex].value === '0') {
                        document.getElementById('tribunal').style.visibility = 'visible';
                    } else  {
                        document.getElementById('tribunal').style.visibility = 'hidden';
                    }
            </script>

Thanks in advance :)

Ad

Answer

You have to add an eventlistener.

let tribunal = document.getElementById("select-tribunal");
tribunal.addEventListener('change', showInput);
showInput({
  target: tribunal
});

function showInput(event) {
  if (event.target.value === '0') {
    document.getElementById('tribunal').style.visibility = 'visible';
  } else {
    document.getElementById('tribunal').style.visibility = 'hidden';
  }
}
<label for="select-tribunal" class="form-label">Cadre Légal</label>
<select id="select-tribunal" required class="form-select" aria-label="Default select example">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="0" selected>Autre Tribunal</option>
</select>
<input type="text" class="form-control" id="tribunal" style="visibility: hidden" placeholder="Entrez le nom du tribunal">

Ad
source: stackoverflow.com
Ad