sandesh phuyal sandesh phuyal - 7 months ago 39
HTML Question

Javascript onclick function does not display text assigned

I am trying to display the text using javascript with the onclick function.

i) When I click on both button it only displays the red color , not the blue one.

ii) As well as, when I click on red button 1st time then it displays the red color and if I choose the red button again then it displays the blue color.

function myFunction() {

if (document.getElementById("demo").value == "11") {
document.getElementById("flight").innerHTML = "<p style='color:red'>Red Color</p>";

if (document.getElementById("demo").value == "22") {
document.getElementById("flight").innerHTML = "<p style='color:blue'>Blue Color</p>";


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


As you can see in the comments, an ID should be unique. Otherwise, it will screw up your JS.

I suggest you pass the current DOM element to your function, and use it like so:

function myFunction(elem) {
  switch(elem.getAttribute('value')) {
    case "11":
      document.getElementById("flight").innerHTML = "<p style='color:red'>Red</p>";
    case "22":
      document.getElementById("flight").innerHTML = "<p style='color:blue'>Blue</p>";
<button onclick="myFunction(this)" value="11">Red</button>
<button onclick="myFunction(this)" value="22">Blue</button>
<div id="flight"></div>