title: How prevent submit if input are empty with javascript
body: <p>I have a login form but I wanna check if the fields are empty then do not submit. I did `return false' on submit but the browser still loads a new page. How can I stop that?</p>
  
  <p>JS:</p>
  
  <pre><code>var username = document.getElementById('usernameField');
      var password = document.getElementById('passwordField');
      var loginBtn = document.getElementById('loginBtn');
      var infoBox = document.getElementById('formInfo');
  
      var isEmpty = /^\s*$/;
  
      var addEventTo = function(id, type, fn, capture) {
          if (document.addEventListener) {
              id.addEventListener(type, fn, capture);
          } else {
              id.attachEvent('on'+type, fn);
          }
      };
  
      function checkIfAllEmpty() {
          var loginForm = document.getElementById('loginform'),
              allInputs = loginForm.getElementsByTagName('input'),
              max = allInputs.length,
              i;
  
              for (i = 0; i &lt; max; i++) {
                  if (allInputs[i].type !== 'submit') {
  
                      if (allInputs[i].match(isEmpty)) {
                          infoBox.innerHTML = 'All your fields are empty';
                          return false;
                      }
              }
          }
      }
  
      //addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
  
      if (document.addEventListener) {
              loginBtn.addEventListener('submit', checkIfAllEmpty, false);
      } else {
              loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
      }
  </code></pre>
  
  <p>HTML:</p>
  
  <pre><code>&lt;p id="formInfo"&gt;&lt;/p&gt;
  &lt;form id="loginForm" method="post" action="#"&gt;
      &lt;fieldset id="loginFieldset"&gt;
          &lt;legend&gt;Sign in&lt;/legend&gt;
          &lt;ol&gt;
              &lt;li&gt;
                  &lt;label for="usernameField"&gt;Username&lt;/label&gt;&lt;input type="text" placeholder="Enter username" id="usernameField" /&gt;
                  &lt;span&gt;Please type in your username&lt;/span&gt;
              &lt;/li&gt;
              &lt;li&gt;
                  &lt;label for="passwordField"&gt;Password&lt;/label&gt;&lt;input type="password" placeholder="Enter password" id="passwordField" /&gt;
                  &lt;span&gt;Please type your password&lt;/span&gt;
              &lt;/li&gt;
              &lt;li&gt;
                  &lt;input type="submit" value="Sign in" id="loginBtn" /&gt;
              &lt;/li&gt;
          &lt;/ol&gt;
      &lt;/fieldset&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Many thanks</p>