简体   繁体   中英

Javascript alert based on prompt value

I am trying to make a script in which a prompt window will pop up asking a question, and based on what the answer in it is, an alert box will pop up saying that the answer is valid or invalid. In my code, my prompt box works, but my alert box didn't. Can someone help me solve this problem please? Thank you so so much!!

<!DOCTYPE HTML>
<html>
<script type="text/javascript">
var City=prompt("Enter your city", "City");
function checkName(){
    var validLetters=/^[a-z]+$/i;
    if(validLetters.test(City))
        alert("Your input is accepted!");
    else
        alert("Your input is invalid!");
}
</script>

Invoke the function checkName with argument City or you could use global-variable .

You are not calling the function in your script to test the value of prompt

 var City = prompt("Enter your city", "City"); checkName(City); function checkName(City) { var validLetters = /^[az]+$/i; if (validLetters.test(City)) alert("Your input is accepted!"); else alert("Your input is invalid!"); } 

You are not calling your fucntion checkName . call this function after prompt .

var City = prompt("Enter your city", "City");

checkName(City);  // function to be called 

function checkName(City) {
  var validLetters = /^[a-z]+$/i;
  if (validLetters.test(City))
    alert("Your input is accepted!");
  else
    alert("Your input is invalid!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM