Home > Back-end >  Why isn't my Javascript function running when I hit the button
Why isn't my Javascript function running when I hit the button

Time:12-23

I'm creating a website and the index page is a textbox with a button, when the button is pressed, it's supposed to load a different html file depending on if the code is right or not. However, when I press the button, it doesn't work.

This is my JS Code:

//Code : (Z@D0L3$%)
console.log("Hello World!");
function CheckCode() {
  var code = document.getElementById('TextBox').value;
  var correctCode = "(Z@D0L3$%)";
  if (code == correctCode) {
    window.location.href = 'correct.html';
  }
  else {
    window.location.href = 'incorrect.html';
  }
}

function BackToIndex() {
  window.location.href = 'index.html';
}

This is my HTML code for the button

<input type="text" id="TextBox" name="TextBox">
  <button id="mybutton" onclick="CheckCode();">Submit Code</button>

CodePudding user response:

There are a few things that could be causing the issue you're experiencing. Here are a few potential causes and some things you can try to resolve the problem:

Make sure that the HTML file for the correct and incorrect pages exist and are in the correct location. If the files are not found, the JavaScript code will not be able to redirect the user to them.

Make sure that the correct spelling and capitalization is used for the file names in the window.location.href assignments. If the file names are not spelled correctly, the JavaScript code will not be able to find them.

Make sure that the JavaScript code is being run when the button is clicked. One way to do this is to add a console.log statement at the beginning of the CheckCode function, and then check the JavaScript console to see if the message is being logged when the button is clicked.

Make sure that the TextBox element has the correct id attribute. If the id attribute is not spelled correctly or is not set correctly, the JavaScript code will not be able to find it.

Make sure that the TextBox element is correctly placed within the HTML page. If the element is placed outside of the element or is not correctly nested within other elements, the JavaScript code may not be able to find it.

I hope this helps! Let me know if you have any other questions or if these suggestions do not resolve the issue.

CodePudding user response:

code looks fine to me.. didn't find any errors

CodePudding user response:

Here are not errors. If you don't see in console hello world, You are not correctly importing javascript in your html file

  • Related