0

I am trying to check if a variable exists before allowing the form to submit.

Currently, the user enters the address into the form and autocomplete adds lat and long to the form. I wrote the following js

function check() {
    let latitude = document.getElementById("latitude").value;
    if (latitude == null) {
        window.prompt("ned a correct address", "");
        return false;
    } else {
        alert('It worked');
        return true;
    }
}

When I submit an address that doesn't have the lat and long autocompleted I am still getting "it worked"

Here is my form

<form method="GET" action="/search" onsubmit="check()">
    <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
    <input id="latitude" type="hidden" name="latitude">
    <input id="longitude" type="hidden" name="longitude">
</form>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Chris Grim
  • 149
  • 1
  • 6
  • 20

2 Answers2

2

If you really want to check if a variable exists or not, there is a safe way to do so, by using:

if(variable) {
  // Truthy
} else {
  // Falsy
}

This way, you get all the possible Falsy scenarios including: null, undefined, NaN, "", 0 and finally the false itself... Without checking for each one of them!

Here is the edited snippet:

function check() {
  let latitude = document.getElementById("latitude").value;
  if (latitude) {
    alert('It worked');
    return true;
  } else {
    window.prompt("ned a correct address", "");
    return false;
  }
}
<form method="GET" action="/search" onsubmit="check()">
  <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
  <input id="latitude" type="hidden" name="latitude">
  <input id="longitude" type="hidden" name="longitude">
</form>

*This code will execute ONCE only!

Elharony
  • 886
  • 8
  • 18
  • If you were interested in brevity, you could simply do `return !!latitude` instead of the entire `if` portion :) You'd lose the alert though. – Tyler Roper Nov 06 '18 at 02:35
  • Amazing! This did it. Thanks so much – Chris Grim Nov 06 '18 at 03:01
  • The OP isn't really testing for whether a variable exists, but whether something has been entered into a form control. In that case, the value should be tested according to suitable criterial, so `if (latitude == '')` would be preferred as when the test is executed, its value must be a string. Though it would also be better to test `-90 <= latitude <= +90`. – RobG Nov 06 '18 at 04:25
0

There are a few things to consider here for more reliable form validation;

  1. Suggest using the event object to cancel the submit action if validation fails
  2. Validate input fields value via a test for the "empty string" rather than null
  3. Ensure no errors are thrown in your script (ie ensure geo() is defined, etc) so that check() actually gets called rather than silently failing to be called due to another script error

The following changes might help:

// Pass event object
function check(event) {
  
  let address = document.getElementById("getaddy").value;
  
  // Check for empty string, rather than null
  if (address === '') { 
    window.prompt("ned a correct address", "");
      
    // Use Event#preventDefault() to prevent submit
    // as a more reliable alternative to returning 
    // false
    event.preventDefault();
  } else {
  
    alert('It worked');
  }
}


// Ensure geo() is defined, seeing your form is relying on this
function geo() { }
<!-- update check call to pass event object -->
<form method="GET" action="/search" onsubmit="check(event)">

  <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
  <input id="latitude" type="hidden" name="latitude">
  <input id="longitude" type="hidden" name="longitude">
  
</form>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65