Search code examples
javascripthtmldropdown

Show default value with HTML dropdown


I created a dropdown. Like this, the dropdown shows 1 as default value in the dropdown, but I also want to show the value assigned to that showing before I selected anything in the first place. This means, before I've clicked anything, I want it to show "You selected: one" by default. How do I do this best?

function myFunction() {
  var x = document.getElementById("mySelect").value;
  if (x == "one") {
    document.getElementById("demo").innerHTML = "You selected: " + x;
  } else if (x == "two") {
    document.getElementById("demo").innerHTML = "You selected: " + x;
  } else if (x == "three") {
    document.getElementById("demo").innerHTML = "You selected: " + x;
  }
}
<select name="test" id="mySelect" onchange="myFunction()">
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
</select>
<p id="demo"></p>

thank you!


Solution

  • just call myFunction() onload

    function myFunction() {
      var x = document.getElementById("mySelect").value;
    
      if (x == "one") {
        document.getElementById("demo").innerHTML = "You selected: " + x;
      } else if (x == "two") {
        document.getElementById("demo").innerHTML = "You selected: " + x;
      } else if (x == "three") {
        document.getElementById("demo").innerHTML = "You selected: " + x;
      }
    }
    
    myFunction(); // call onload
    <select name="test" id="mySelect" onchange="myFunction()">
      <option value="one">1</option>
      <option value="two">2</option>
      <option value="three">3</option>
    </select>
    
    <p id="demo"></p>


    Updated remove if statement

    function myFunction() {
      var x = document.getElementById("mySelect").value;
    
      document.getElementById("demo").innerHTML = "You selected: " + x;
    }
    
    myFunction(); // call onload
    <select name="test" id="mySelect" onchange="myFunction()">
      <option value="one">1</option>
      <option value="two">2</option>
      <option value="three">3</option>
    </select>
    
    <p id="demo"></p>