Aman Kaur
Aman Kaur

Reputation: 1

Uncaught ReferenceError : I am trying to use a button with OncLick method in JavaScript but keep getting error ,

I am trying to get a message when the button is clicked but I keep getting errors in my console and the button is not working. It's my first week in learning js.

The error I am getting in console is:

Uncaught ReferenceError: purchase is not defined at HTMLButtonElement.onclick (shoe.html:10:32)

let showMessage = document.getElementById("error=el");
let message = " sorry some error!"
function purchase(){
  //console.log('clicked');
  showMessage.textContent = message;
}
purchase();
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button onclick="purchase()">Purchase</button>  
  <p Id="error-el"></p>

</body>
</html>

Upvotes: 0

Views: 812

Answers (2)

Jijo Alexander
Jijo Alexander

Reputation: 1290

There are some small mistakes in the code that I fixed,

  • The id attribute should be in lower case
  • In getting element by Id function you're looking for error=el instead of error-el. The problem here was the = instead of -

let showMessage = document.getElementById("error-el");
let message = " sorry some error!"
function purchase(){
  showMessage.textContent = message;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button onclick="purchase()">Purchase</button>  
  <p id="error-el"></p>

</body>
</html>

Upvotes: 1

KrohnicDev
KrohnicDev

Reputation: 370

To use JavaScript in your HTML, you should load the script from another file using a <src> tag or write it directly into the .html file with a <script> tag.

Upvotes: 0

Related Questions