title: Dynamic Form Validation using javascript
body: <p>Its the newbie again.. I am trying to design a form that takes a username and a password and validates them. However first i want to make sure that the user fills in both the fields before i pass it on to the servlet or any other server related component. I wish to do so using javascript which generates an alert button, more like a JOptionPane when either or both the fields are empty. My code is </p>
  
  <hr>
  
  <p>index.jsp</p>
  
  <hr>
  
  <pre><code>&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
      &lt;title&gt;JSP Page&lt;/title&gt;
      &lt;script src="newjavascript.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;h1&gt;Hello World!&lt;/h1&gt;
      &lt;form id="form" method="post" action="final.jsp"&gt;
      Student name :&lt;br&gt;&lt;input type="text" value="" name="username"   id="idusername"&gt;&lt;br&gt;&lt;br&gt;
      Password :&lt;br&gt;&lt;input type="text" value="" name="password" id="idpassword"&gt;&lt;br&gt;&lt;br&gt;
      &lt;input type="submit" value="Register" /&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <hr>
  
  <p>I pass the above onto a javascript file newjavascript.js which is</p>
  
  <hr>
  
  <pre><code>$(document).ready(function(){
  var form = $("#form");
  var username = $("#idusername");
      var password = $("idpassword");
  //On Submitting
  form.submit(function(){
      if(validateName() &amp; validatePassword())
          return true;
      else
      {
          alert('Some fields are not filled correctly. Please fill them correctly.');
          return false;
      }
  });
  
  function validateName(){
  
      if(username.val().length &lt; 1){
          return false;
      }
  
      else{
          return true;
      }
  }
  
      function validatePassword(){
  
  
      if(password.val().length &lt;5){
          return false;
      }
  
      else{           
          return true;
      }
  }
  });
  </code></pre>
  
  <hr>
  
  <p>Is my javascript code wrong or i am not properly able to pass on the parameters to it ??</p>