Home > Back-end >  Display specific based based on drop-down menu selection
Display specific based based on drop-down menu selection

Time:12-06

I'm creating static changes here. I made a drop-down menu in HTML with two options, One and Two. If the user selects One, then "x" should display once. If the user selects Two, then "xx" should be displayed. However, both "x" and "xx" display on the page before and after the user selects a menu option. How can I create a condition-like environment around my HTML code?

Below is the code I wrote to try to make the display scenario display "x" or "x" depending on the user's selection. The first six lines contain the code for the drop-down menu:

<div>
  <select id="options-in-menu">
    <option value="one">One</option>
    <option value="two">Two</option>
  </select>
</div>

<div id="selected-option">
  <div id="one">
    <p>x</p>
  </div>
  <div id="two">
    <p>xx</p>
  </div>
</div>

The actual results include a blank page.

CodePudding user response:

You can make this feature you want using javascript. I have added sample code for you, you can proceed by looking at it. I wrote myFunction with javascript. I have run myFunction with onchange function. it works every time there is a change and changes the display property of the divs.

    <div>
  <select id="options-in-menu" onchange="myFunction()">
    <option value="one">One</option>
    <option value="two">Two</option>
  </select>
</div>

<div id="selected-option">
  <div id="one">
    <p>x</p>
  </div>
  <div id="two">
    <p>xx</p>
  </div>
</div>

<script>
function myFunction() {
  var val = document.getElementById("options-in-menu").value;
  document.getElementById("one").style.display = "none";
  document.getElementById("two").style.display = "none";
  document.getElementById(val).style.display = "block";
}
</script>

CodePudding user response:

If you can use JS, this should work:

<div>
  <select id="options-in-menu" onchange="optionChange()">
    <option value="one">One</option>
    <option value="two">Two</option>
  </select>
</div>

<div id="selected-option">
  <div id="one">
    <p>x</p>
  </div>
  <div id="two">
    <p>xx</p>
  </div>
</div>

<script>
    let elSelectedOption = document.getElementById("selected-option");
    let elOptionsInMenu = document.getElementById("options-in-menu");
    function optionChange() {
        for (var child of elSelectedOption.children) {
            child.style.display = "none";
        }
        document.getElementById(elOptionsInMenu.value).style.display = "block";
    }
</script>

We set the display style on all of the elements to none, and then set the element with the same id as the selected value to block, and don't immediately update it to show both. The onchange event is fired when the user picks something from the drop down.

  • Related