title: jQuery: prevent form submission if the field before submit button is empty
body: <p>I've just started learning jQuery and already love it, but my skills aren't enough yet to solve this probably simple problem for my work: I have 3 different forms with an input field immediately followed by submit button:</p>
  
  <p><img src="https://i.stack.imgur.com/Eqvmb.png" alt="alt text"></p>
  
  <p>I would like to prevent form submission if the text input field or the textarea before the submit button is empty. I've stolen a snippet from the <a href="http://www.sitepoint.com/books/jquery1/" rel="nofollow noreferrer">jQuery Ninja book</a>:</p>
  
  <pre><code>$(function() { 
          $(':submit').click(function(e) {
                  $(':text').each(function() {
                          if ($(this).val().length == 0) {
                                  $(this).css('border', '2px solid red');
                          }
                  });
                  e.preventDefault();
          });
  });
  </code></pre>
  
  <p>But it has following problems:</p>
  
  <ol>
  <li>It ignores the textarea in the last form, because <code>$(':text').each()</code> does not apply to it</li>
  <li>It doesn't allow submitting any form - I guess I need to move <code>preventDefault()</code> under an "if"</li>
  <li>I probably should better use <code>prev()</code> instead of <code>each()</code></li>
  <li>If the user changes her mind and clicks another form, the previous form should be cleared</li>
  </ol>
  
  <p>Could someone help me please? Alex</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I've tried:</p>
  
  <pre><code>$(function() {
          $(':submit').click(function(e) {
                  $(this).prev(function() {
                          if ($(this).val().length &lt; 2) {
                                  // would be good to clear border for
                                  // each text and textarea here...
                                  $(this).css('border', '2px solid red');
                                  e.preventDefault();
                          }
                  });
          });
  });
  </code></pre>
  
  <p>but unfortunately get 2 warnings:</p>
  
  <pre><code>Warning: Unexpected token in attribute selector: '!'.
  Warning: Unknown pseudo-class or pseudo-element 'submit'.
  </code></pre>
  
  <p>and the red border doesn't appear and the form is submitted when a button is clicked.</p>
  
  <p>Also I've tried:</p>
  
  <pre><code>$(function() {
          $('form').submit(function(e) {
                  $(':text, textarea').each(function() {
                          if ($(this).val().length &lt; 2) {
                                  $(this).css('border', '2px solid red');
                                  e.preventDefault();
                          }
                  });
          });
  });
  </code></pre>
  
  <p>but the form is never submitted and all 3 text fields turn red instead of just one.</p>