Home > OS >  I have an Issue with my onclick function in JavaScript
I have an Issue with my onclick function in JavaScript

Time:12-17



<html>
    <head><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <img src="images/shoe.jpeg" alt="Nike shoe">
        <p>Nike shoe</p>
        <button>Purchase - $149</button>
        <p id="error" onclick="purchase()"></p>
        <script>

       // When the user clicks the purchase button, render out
       // "Something went wrong, please try again" in the paragraph
       // that has the id="error".


       let errorID = document.getElementById("error")
       console.log(errorID)

       function purchase() {
       console.log("Button is clicked")
       errorID.textContent =  "Something went wrong, please try again"
            }


       </script>
    </body>
</html>


So when the button is clicked it's supposed to render an error message inside the p tag as stated in the javascript. I even grabbed the id properly and stated everything correctly but It's not working. I can't seem to find the issue

When I wanted to click on a button it did not work

CodePudding user response:

You're onclick needs to be on the button, not the p

let errorID = document.getElementById("error")
console.log(errorID)

function purchase() {
       console.log("Button is clicked")
       errorID.textContent =  "Something went wrong, please try again"
}
<button onclick="purchase()">Purchase - $149</button>
<p id="error"></p>
       

CodePudding user response:

Nike shoe

Purchase - $149

   // When the user clicks the purchase button, render out
   // "Something went wrong, please try again" in the paragraph
   // that has the id="error".


   let errorID = document.getElementById("error")
   console.log(errorID)

   function purchase() {
   console.log("Button is clicked")
   errorID.textContent =  "Something went wrong, please try again"
        }


   </script>
</body>

Correct code is this please see syntax call onclick on button

  • Related