I’m having a hard time understanding why my alert is popping up without pressing the button and also why I am not able to get the text from the input box to use in my functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Palindrome Checker</title>
<link rel="stylesheet" type="text/css" href="./styles.css">
</head>
<body>
<header>
<h1 id="title">Christian's palindrome checker</h1>
<h2>Type a word or sentence below and click the button to check if it is a palindrome.</h2>
</header>
<form>
<input type="text" id="text-input">
<br />
<button id="check-btn" >Check!</button>
<p id="result"></p>
</form>
<script src="./script.js"></script>
</body>
</html>
html {
font-size: 62.5%;
font-family: sans-serif;
text-align: center;
}
h1 {
font-size: 4rem;
}
h2 {
font-size: 2rem;
}
const userInput = document.getElementById("text-input").value;
const checkButton = document.getElementById("check-btn");
const resultText = document.getElementById("result")
function cleanString(string) {
const regex = /[^a-zA-Z0-9]/gi;
const lowerCaseString = string.toLowerCase()
return lowerCaseString.replace(regex, "");
}
function checkForPalindrome(userInput) {
if (userInput === "") {
return alert("Please input a value")
} else {
const cleanText = cleanString(userInput);
const cleanTextArray = cleanText.split("");
const reverseTextArray = cleanTextArray.reverse();
const reverseText = reverseTextArray.join("");
if (reverseText === cleanText) {
return resultText.innerText = `${userInput} is a palindrome`;
} else {
return resultText.innerText = `${userInput} is not a palindrome`;
}
}
}
checkButton.onclick = checkForPalindrome(userInput);