Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what’s happening:

I don’t understand why this code can’t pass the test:
When you click on the #check-btn element without entering a value into the #text-input element, an alert should appear with the text “Please input a value”
I run the code in jsfiddle.net and it alert and appear what the test ask, but why on freecodecamp.org nothing happened

Your code so far

<!-- file: index.html -->
 <!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css"/>
    <script src="script.js"></script>
  </head>
  <body>
    <input type = "text" id = "text-input"></input>
    <button id = "check-btn" onclick = "checkButton()">Check</button>
    <div id = "result"></div>
  </body>
</html>
/* file: script.js */
const checkBtn = document.getElementById("check-btn"); // Const button element
const textInput = document.getElementById("text-input");
const alphanumericChars= /[a-zA-Z0-9]/g; // [] regex character class and global flag
const result = document.getElementById("result");

function checkButton() {
    if (textInput.value === "") {
    	alert("Please input a value");
    }
} 

checkBtn.addEventListener("click",checkButton);
/* file: styles.css */

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36

Challenge Information:

Build a Palindrome Checker Project - Build a Palindrome Checker

Hi @magicturtlevn

I think it’s because the script executes before the HTML is fully parsed. If you check in the browser console, you will notice Type errors. By the time the script runs, the elements you are selecting are still null.

VM775:8 Uncaught
TypeError: Cannot read properties of null (reading ‘value’)
at checkButton (:8:17)
at HTMLButtonElement.onclick

Try moving the script element to the end of the body element, just before the closing </body> tag. I suspect the difference in behavior between FCC and JSFiddle is because of the way the scripts are loaded.

1 Like

Thank you, it’s really confused. You know, sometimes what I learned before can’t help. In this situation, what I learned on HTML/CSS course fCC against me.

1 Like