skip to Main Content

I’m relatively new to JavaScript and cannot identify the problem I’m having with displaying the correct text in the #results field and textInput picking up anything other than an undetermined value or "[object HTMLInputElement] is a palindrome".

I’ve tried fixing it with several of the options found on here including using .toString(), .innerHTML vs .textContent, etc.

let textInput = document.getElementById("text-input").toString();
const checkBtn = document.getElementById("check-btn");
const results = document.getElementById("results");
const clearBtn = document.getElementById("clear");

function checkPalindrome() {
    if (textInput.value === undefined) {
      alert("Please input a value");
      results.innerHTML = "Invalid Input";
      return;
  };

  const inputString = textInput?.toString().replace('"/,.-=+_][}{)(;:?><!@#$%^&* ').toLowerCase().value;
  const reversedString = textInput?.toString().split("").reverse().join("").value;

  if (inputString === reversedString) {
    results.innerHTML = `${textInput} is a palindrome`;
  } else {
    results.innerHTML = `${textInput} is not a palindrome`;
  };
};

function clearText() {
    textInput.value = "";
    results.innerHTML = "";
}

checkBtn.addEventListener("click", checkPalindrome);
clearBtn.addEventListener("click", clearText);
<div id="container">
  <h1>Palindrome Checker</h1>
  <input type="text" id="text-input" placeholder="Enter a word or phrase" />
  <button onclick="checkPalindrome()" id="check-btn">Check</button>
  <div id="result"><h2 id="results"></h2></div>
  <div id="clear"><button onclick="clearText()" id="clear-btn">Clear</button></div>
</div>

2

Answers


  1. I fixed the mistakes below – see inline comments for details.

    const textInput = document.getElementById('text-input'); // Don't call toString()
    const checkBtn = document.getElementById('check-btn');
    const results = document.getElementById('results');
    const clearBtn = document.getElementById('clear');
    
    function checkPalindrome() {
      // Check if falsey (empty string, null, undefined etc.)
      if (!textInput.value) {
        alert('Please input a value');
        results.innerHTML = 'Invalid Input';
        return;
      }
    
      // Copy and sanitize the value
      const sanitizedString = textInput.value
        // Remove special characters
        .replaceAll(/["/,.-=+_][}{)(;:?><!@#$%^&* ]/g, '')
        .toLowerCase();
      const reversedString = sanitizedString.split('').reverse().join('');
    
      // Reference the sanitized value when checking for palindrome
      // Reference the original value in output
      if (sanitizedString === reversedString) {
        results.innerHTML = `${textInput.value} is a palindrome`;
      } else {
        results.innerHTML = `${textInput.value} is not a palindrome`;
      }
    }
    
    function clearText() {
      textInput.value = '';
      results.innerHTML = '';
    }
    
    checkBtn.addEventListener('click', checkPalindrome);
    clearBtn.addEventListener('click', clearText);
    <!-- You already added onclick listeners in js, don't add them here -->
    <div id="container">
      <h1>Palindrome Checker</h1>
      <input type="text" id="text-input" placeholder="Enter a word or phrase" />
      <button id="check-btn">Check</button>
      <div id="result"><h2 id="results"></h2></div>
      <div id="clear">
        <button id="clear-btn">Clear</button>
      </div>
    </div>
    Login or Signup to reply.
  2. The problems: first of all in your code, you put the <script> tag outside the <body> tag when it is supposed to be inside. Second of all, in the text-input variable, you tried to toString() a element which doesn’t make sense. I replaced it with only the element. Then I also made a variable which stores the value of text-input to make the code cleaner. Also, I put a blank string checker instead of undefined because when you check it never puts undefined it puts a blank string if you don’t enter anything.

    The code

    let textInput = document.getElementById("text-input");
    const checkBtn = document.getElementById("check-btn");
    const results = document.getElementById("results");
    const clearBtn = document.getElementById("clear");
    
    function checkPalindrome() {
        value = textInput.value;
        if (value === undefined || value == "") {
          alert("Please input a value");
          results.innerHTML = "Invalid Input";
          return;
      };
    
      const inputString = value?.toString().replace('"/,.-=+_][}{)(;:?><!@#$%^&* ').toLowerCase();
      const reversedString = value?.toString().split("").reverse().join("");
    
      if (inputString === reversedString) {
        results.innerHTML = `${textInput.value} is a palindrome`;
      } else {
        results.innerHTML = `${textInput.value} is not a palindrome`;
      };
    };
    
    function clearText() {
        textInput.value = "";
        results.innerHTML = "";
    }
    
    checkBtn.addEventListener("click", checkPalindrome);
    clearBtn.addEventListener("click", clearText);
    <!doctype html>
    <html lang="en">
    
    <head>
        <link rel="stylesheet" href="palindromeCheckerCSS.css" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/darkly/bootstrap.min.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Palindrome Checker</title>
    </head>
    
    <body>
        <div id="container">
            <h1>Palindrome Checker</h1>
            <input type="text" id="text-input" placeholder="Enter a word or phrase">
            <button onclick="checkPalindrome()" id="check-btn">Check</button>
            <div id="result"><h2 id="results"></h2></div>
            <div id="clear"><button onclick="clearText()" id="clear-btn">Clear</button></div>
        </div>
    </body>
    
    
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search