sandesh phuyal sandesh phuyal - 3 months ago 13
HTML Question

Javascript display form before onclick function also

In this case, I have defined on-click function to display the simple two form.

Help me on

How can I always display first form (displayRed function form) before onclick function .

<button onclick="displayRed()" value="11">Red</button>
<button onclick="displayBlue()" value="22">Blue</button>
<div id="flight"></div>

function displayRed() {
document.getElementById("flight").innerHTML = "<form> <input type='text' value='1'/> </form>";
}

function displayBlue() {
document.getElementById("flight").innerHTML = "<form> <input type='text' value='2'/> </form>";
}

Answer

On your body element:

<body onload="displayRed()">
  <!-- everything else ...

MDN says:

onload
Function to call when the document has finished loading.

So by adding the onload attribute to your body element you execute that javascript function as soon as the page is loaded.

function displayRed() {
  alert("Red!");
}

function displayBlue() {
  alert("Blue!");
}
<body onload="displayRed()">
  <button onclick="displayRed()" value="11">Red</button>
  <button onclick="displayBlue()" value="22">Blue</button>
  <div id="flight"></div>
</body>

Comments