Why does this not function correctly?
No matter what value you enter it ALWAYS returns "Invalid Ticket Type"
Use &&
instead of ||
if (TickType != "A" || TickType != "B" || TickType != "C"){
document.getElementById("msg").innerHTML = "Invalid Ticket Type";
}
Explanation
When TickType = "A"
, TickType != "B"
and TickType != "C"
conditions are true.
Here two of the condition is always true
, so it goes into the if
statement
NOTE: Add a trim and a parseInt to the vars and value=""
to the fields and emptied the message before testing
function start() {
var TickType = document.getElementById("TicketType").value.trim();
var TicketQty = parseInt(document.getElementById("TicketQty").value, 10);
document.getElementById("msg").innerHTML = "";
if (TickType != "A" && TickType != "B" && TickType != "C") {
document.getElementById("msg").innerHTML = "Invalid Ticket Type";
}
if (isNaN(TicketQty)) {
document.getElementById("msg").innerHTML = "Non numeric qty has been entered";
}
if (TicketQty < 1 || TicketQty > 100) {
document.getElementById("msg").innerHTML = "Qty is outside valid range";
}
}
<h1>Ticket Sales</h1>
<p>Enter the ticket type (A, B or C)</p>
<input type="text" id="TicketType" value="" />
<p>Enter the quantity required (1-100)</p>
<input type="text" id="TicketQty" value="" />
<p><br/></p>
<button onclick="start()">Click me</button>
<p id="msg"></p>