Bear with me guys.. Im new to JavaScript AND StackOverflow...

Here is my problem :

I have created a simple piece of code, with 3 buttons that should change a text (innerHTML) when pressed... but it's not working.. :-(

What am I doing wrong ?

I have checked W3Schools for clues.. but no dice..

<head>
  <title>JavaScript Table</title>
  <style>
    body{
        text-align: center;
        font-family: arial;
    }
  </style>
        <script>
            function red(){
                document.getElementById("tekst").innerHTML = "Red";
            }
            function green(){
                document.getElementById("tekst").innerHTML = "Green";
            }
            function blue(){
                document.getElementById("tekst").innerHTML = "Blue";
            }
        </script>
</head>
<body>
        <h2 id="tekst">Color</h2>
        <button onsubmit="red()">Red</button>
        <button onsubmit="green()">Green</button>
        <button onsubmit="blue()">Blue</button>     
</body>
</html>```

3 Answers

0
Mark Minerov On Best Solutions

You need to change onsubmit to onclick. You can also add an event in the script:

HTML:

<h2 id="text">Color</h2>
<button id="red">Red</button>
<button id="green">Green</button>
<button id="blue">Blue</button>`

JavaScript:

document.getElementById("red").addEventListener("click", () => 
document.getElementById("text").innerHTML = "RED")

document.getElementById("green").addEventListener("click", () => 
document.getElementById("text").innerHTML = "GREEN")

document.getElementById("blue").addEventListener("click", () => 
document.getElementById("text").innerHTML = "BLUE")
2
Maheer Ali On

You need to change onsubmit to onclick.

You can shorten the code by using addEventListener. You can create array of texts and use forEach loop to add listeners to buttons to change the text to the element of array at particular index.

const arr = ["Red","Green","Blue"]
const h2 = document.querySelector('#tekst');
document.querySelectorAll('button').forEach((x,i) => {
  x.addEventListener('click',() => h2.innerHTML = arr[i])
})
<head>
  <title>JavaScript Table</title>
  <style>
    body{
        text-align: center;
        font-family: arial;
    }
  </style>
        <script>
            
        </script>
</head>
<body>
        <h2 id="tekst">Color</h2>
        <button>Red</button>
        <button>Green</button>
        <button>Blue</button>     
</body>

0
Community On
   <button onclick="red()">Red</button>
   <button onclick="green()">Green</button>
   <button onclick="blue()">Blue</button>

Please replace with onclick instead of onsubmit.