Tudor Apostol
Tudor Apostol

Reputation: 45

Trying to find if a number is a palindrome in JS

I'm trying to learn JS and I have a few exercises that I'm trying to solve in order to improve. At the moment, I'm trying to find out if a number is palindrome, and I have this code, but it doesnt seem to work, since I get that all the numbers I insert in the inputs are palindromes.

<input type="text" class="screen">
<button type="button" class="btn">Check</button>


 var strg = document.querySelector(".screen").value;
 var pal = strg.split("").reverse("").join("");

document.querySelector(".btn").addEventListener("click", function(){
    if (strg == pal) {
    console.log(strg+" is a palindrome");
  }
  else {
    console.log(strg+" is not a palindrome");
  }
})

https://jsfiddle.net/Lw6uk8kb/

Appreciate the help.

Upvotes: 0

Views: 961

Answers (3)

vp_arth
vp_arth

Reputation: 14992

You didn't update your variables with actual values.
Just move them inside event handler:

document.querySelector(".btn").addEventListener("click", function(){
 var strg = document.querySelector(".screen").value;
 var pal = strg.split("").reverse().join("");
 if (strg == pal) {
   console.log(strg+" is a palindrome");
 } else {
   console.log(strg+" is not a palindrome");
 }
})

Upvotes: 0

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3655

Use code as below:

document.querySelector(".btn").addEventListener("click", function(){
    var strg = document.querySelector(".screen").value;
    var pal = strg.split("").reverse("").join("");
    if (strg == pal) {
    console.log(strg+" is a palindrome");
  }
  else {
    console.log(strg+" is not a palindrome");
  }
})

This will work because you will calculate palindrome at moment (after) you click on button. In your code all computation works at once after all scripts are loaded.

Upvotes: 1

Halcyon
Halcyon

Reputation: 57703

You have to move the first two lines inside the handler as well:

document.querySelector(".btn").addEventListener("click", function(){
    var strg = document.querySelector(".screen").value;
    var pal = strg.split("").reverse("").join("");
    if (strg == pal) {
        console.log(strg+" is a palindrome");
    }
    else {
        console.log(strg+" is not a palindrome");
    }
});

else you will always query the same (empty?) value of .screen.

Upvotes: 2

Related Questions