Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what’s happening:

I know my palindrome checker works when I hardcode an input variable, and it will update the innerHTML text with the appropriate value based on that input variable. But when I switch to using input = document.getElementById(“text-input”).value it breaks and what happens is it will always show the alert no matter what is entered in the text box. I don’t think I’m importing the input box text correctly since the code is always reading it as null instead of whatever I input. Any help on how to fix this?

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="styles.css">
    <title>Palindrome Checker</title>
  </head>
  <body>
    <main>
     <h1>Is it a Palindrome?</h1>
    <input 
      type="text" 
      id="text-input" 
    />
    <button id="check-btn">Check</button>
    <div id="result"></div>
    </main>
  </body>
      <script src="script.js"></script>
</html>
/* file: styles.css */

/* file: script.js */
const checkButton = document.getElementById("check-btn");
const input = document.getElementById("text-input").value;
const result = document.getElementById("result");


// check if palindrome and update div text
function palindrome(str) {

  // lowercase and remove alphanumerics
  const alphanumericArray = str.toLowerCase().match(/[a-z0-9]/g);
  const cleanString = alphanumericArray.join("");
  const reverseString = alphanumericArray.reverse().join("");

  //check for palindrome
  if (cleanString === reverseString) {
    result.innerHTML = `${input} is a palindrome`;
  } else {
    result.innerHTML = `${input} is not a palindrome`;
  }
};


// check if string is empty
function validInput() {
  if (input === "") {
    alert("Please input a value");
    return;
  } else {
    palindrome(input);
  }
}


checkButton.addEventListener("click", validInput);

Your browser information:

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

Challenge Information:

Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what this is doing.

I thought it was getting the input value from the input field with id “text-input” but it doesn’t seem to be working that way.

You are correct, it is getting the string value in the #text-input, and when that line runs initially, what value is in #text-input? And then where in your code do you check for a new value in #text-input?

1 Like

Ah I see. I won’t post my final solution but it is now working and I passed the tests. Thank you! :slight_smile:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.