Question

My page contains text boxes and a submit button. If the form is submitted, an alert box would pop-out and would state if the inputs are valid or invalid.

Here's the code:

    alert(valid ? "Valid" : "Invalid")

But what I really want is for the page to proceed if the inputs are valid, and the alert box will only pop-out when it's invalid.

Was it helpful?

Solution

You current logic has nothing to do with whether or not the alert is executed. It only determines what the value of the alert is (what string is shown).

if (!valid) {
  alert("Hey, it's invalid!");
}

valid ? "Valid" : "Invalid" is ternary that says: "If valid, use the string 'Valid', else use the string 'Invalid'.

So, if variable valid evaluates to true, it's just like doing this:

alert('Valid');

If valid evaluates to false:

alert('Invalid');

Instead, you want this:

//if "valid" evaluates to false
if (!valid) {
  //alert the user
  alert("Hey, it's invalid!");
  //you could "return false" here to stop the rest of the block from executing
  return false;
}
//if "valid" is true, it just keeps going
//OR you could use an else statement (valid is true)
else {
  //this isn't necessary if you "return false" above
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top