How can I make the first option to be display without clicking the dropdown options?

In the example I would like to have the first option(apple) display as a predetermined text, please help I was trying to do it using mySelec.tselectedIndex = 0 but didn’t work, thanks
codePen
HTML

<form>
  <select id="mySelect" onchange="myFunction()">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
  </select>
</form>

<p id="demo"></p>

JS

function myFunction() {
  var x = document.getElementById("mySelect");
  var i = x.selectedIndex;
  document.getElementById("demo").innerHTML = x.options[i].text;
}

Why not just call myFunction? Unless otherwise specified using the selected attribute in the one of the option elements’ opening tag, the first one will already be selected. Calling the function will cause the first option’s text to be displayed when the page loads.

1 Like

Maybe something like this?

window.onload = function(){
 const select = document.getElementById("mySelect");
 const firstChild = select[0].text
 document.getElementById("demo").textContent += firstChild 
}
function myFunction() {
  var x = document.getElementById("mySelect");
  var i = x.selectedIndex;
  document.getElementById("demo").innerHTML = x.options[i].text;
}

Also, I’d remove the parenthesis in the function,

<select id="mySelect" onchange="myFunction">

pd: previous reply is a better solution.

you are right thanks I used window.onload to charge the function right away

window.onload = myFunction;
function myFunction() {
    var x = document.getElementById("mySelect");
    var i = x.selectedIndex;
    document.getElementById("demo").innerHTML = x.options[i].text
}


thanks for your help very interesting answer

1 Like

You’re welcome, but remember that just issuing

myFunction()

at the end of your code will work too (and it’s only one line!)