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
I fixed the mistakes below – see inline comments for details.
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 thetext-input
variable, you tried totoString()
a element which doesn’t make sense. I replaced it with only the element. Then I also made a variable which stores the value oftext-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