Im tryting to make a simple palindrom checker.
When Im testing in the console it works fine. However when I try to link it with HTML I cannot get it to work. I think this is due to an error extracting the text from the input field in the HTML file...
Javascript:
const str = document.getElementById('input').value;
function reverseString(str){
let string = str.toLowerCase();
let splitStr = string.split('');
let revString = splitStr.reverse('');
let joinStr = revString.join('');
return joinStr;
}
function compare(str){
if (reverseString(str) === str){
document.querySelector("#answer").innerHTML = 'Its a Palindrom';
} else {
document.querySelector("#answer").innerHTML = 'Its not a Palindrom';
}
}
HTML
<body>
<div >
<h1 id="heading">Palendrom Checker</h1>
<h2 id="subtext">Enter a word of phrase!</h2>
<div id="answer">Answer will output here!</div>
<input type="text" id="input" placeholder="Enter your word or phrase here!">
<button type="button" id="submit" onclick="compare(str)">Check!</button>
</div>
</body>
When I change the compare(str)
to output to the console it works fine:
const str = document.getElementById('input').value;
function reverseString(str){
let string = str.toLowerCase();
let splitStr = string.split('');
let revString = splitStr.reverse('');
let joinStr = revString.join('');
return joinStr;
}
function compare(str){
if (reverseString(str) === str){
console.log('Its a Palindrom')
} else {
console.log('Its not a Palindrom')
}
}
CodePudding user response:
You have to retrieve the string from the input at the time you're going to test it, so you have to get it in compare
. How you have it now you're getting the input value before you type in anything.
function compare(){
const str = document.getElementById('input').value;
if (reverseString(str) === str){
document.querySelector("#answer").innerHTML = 'Its a Palindrom';
} else {
document.querySelector("#answer").innerHTML = 'Its not a Palindrom';
}
}