Reputation: 75
I'm trying to create a program that prints out if a word is a palindrome or not, but for some reason it doesn't work.
When I click the button it says that the word is palindrome even if it is not.
I tried to replace the inputString
with a variable and it works.
So I think it's a problem of the line document.getElementById ("word").value
.
var inputString = document.getElementById("word").value;
var textTrue = "It's a palindrome!";
var textFalse = "Sorry, that's not a palindrome.";
//function that return true if the word is palindrome and false if it is not
function isPalindrome(inStr) {
for (let i = 0; i < inStr.length; i += 1) {
if (inStr[i] !== inStr[inStr.length - 1 - i]) {
return false;
}
}
return true;
}
/* function that print "the word is palindrome" if the isPalindrome function returns true
or "the word is not palindrome" if the isPalindrome function returns false */
function clickFunction() {
if (isPalindrome(inputString)) {
console.log(textTrue);
} else {
console.log(textFalse);
}
}
<header>
<h1>PALINDROME WORD CHECKER</h1>
</header>
<input class="inputbox" type="word" id="word" placeholder="input">
<button onclick="clickFunction()"> Check! </button>
<script src="code.js"></script>
Upvotes: 0
Views: 180
Reputation: 224
you can change your input type =" text"
<input class="inputbox" type="text" id="word" placeholder="input">
js file also
function clickFunction() {
var inputString = document.getElementById("word").value;
if (isPalindrome(inputString)) {
console.log(textTrue);
} else {
console.log(textFalse);
}
}
you get definitely result.
Upvotes: 1
Reputation: 5372
You have to read the content of inputString only after you fill in the text and click on your "Check" button. So You have to move the first line:
var inputString = document.getElementById("word").value;
into your function:
function clickFunction() {
var inputString = document.getElementById("word").value;
if (isPalindrome(inputString)) {
console.log(textTrue);
} else {
console.log(textFalse);
}
}
Otherwise, the inputString
is only read when the page loads and never gets updated with the content of the input, and the textbox's initial value is ""
(empty string), which is a palindrome.
Upvotes: 3