简体   繁体   中英

If and Else Statements Always Output If

I was messing around with a previously existing snippet and ran into an issue. Whenever I try to enter an input that doesn't apply the to If statement it always gives me the If output. Also I was looking to, instead of saying approved, have you sent to a URL, like Google for example, and I'm not sure about a solution for either of the two.

 function myFunction() { var a = document.getElementById("text_a").value; if (a == "02035", "02048", "02067") { document.getElementById("answer").innerHTML = "Approved"; } else { document.getElementById("answer").innerHTML = "Our service currently isn't available in your area! Try again soon!"; } } 
 <p>Enter Zip Code </p> <input id="text_a" type="text" /> <p id="answer"></p> <button onclick="myFunction()">Check</button> 

May be you need to change the condition in if statement:

if (a == "02035" || a == "02048" || a == "02067"){
  document.getElementById("answer").innerHTML="Approved";
}
else{
  document.getElementById("answer").innerHTML="Our service currently isn't available in your area! Try again soon!";
}
if (a=="02035","02048","02067")

You can't do like this. There are many ways to check it. You could do like this

function myFunction() {
  var a = document.getElementById("text_a").value;
  var list = ["02035", "02048", "02067"];
  console.log(a)
  if ((list.indexOf(a) > -1)) {
    document.getElementById("answer").innerHTML = "Approved";
  } else {
    document.getElementById("answer").innerHTML =
      "Our service currently isn't available in your area! Try again soon!";
  }
}

I made a sample: https://codepen.io/anon/pen/bWBvMj?editors=1011

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