Search code examples
javascriptfunctiononclickprompt

Changing form input to JavaScript prompt


I have a function to check if a word entered in a text input is a palindrome:

function Palindrome() {
  var revStr = "";
  var str = document.getElementById("str").value;
  var i = str.length;
  for (var j = i; j >= 0; j--) {
    revStr = revStr + str.charAt(j);
  }
  if (str == revStr) {
    alert(str + " is a palindrome");
  } else {
    alert(str + " is not a palindrome");
  }
}
<form>
  Enter a String or Number:
  <input type="text" id="str" name="string" />
  <br />
  <input type="submit" value="Check" onclick="Palindrome();" />
</form>

I would like the user to be prompted for a word, rather than entering a word into a text input, so I changed

var str = document.getElementById("str").value;

to

var str = prompt("Enter a string or number:")

But the prompt does not fire.
Why am I not being prompted for a word?


Solution

  • You need to call Palindrome() at the end of your script. As it currently stands, Palindrome only fires when you click submit:

    <script type="text/javascript">
        function Palindrome() {
            var revStr = "";
            var str = prompt("Enter a string or number:")
            var i = str.length;
            for(var j=i; j>=0; j--) {
                revStr = revStr+str.charAt(j);
            }
            if(str == revStr) {
                alert(str+" is a palindrome");
            } else {
                alert(str+" is not a palindrome");
            }
        }
        Palindrome()
    </script>
    

    JSFiddle