Form submission after Javascript Validation

Just add action="reg.php" in <form> and return val() functions on onclick, also make type="submit" to form submission, like:

<form method="post" action="reg.php">
   <input type="text" id="username" name="username"></input>        
   <button type="submit" onclick="return val()">Sign Up</button>
</form>

and just add return true; in else like:

function val(){

    var uname = document.getElementById('username').value;
    if(!uname){
        document.getElementById("error").innerHTML = "Enter a username";
        return false;
    }
    else{
        return true;
    }
}

You can submit it with form name in else section.

document.myForm.submit();

 var uname = document.getElementById('username').value;
 if (!uname) {
      document.getElementById("error").innerHTML = "Enter a username";
      return false;
 } else {
      document.myForm.submit(); // Form will be submitted by it's name
 }

Markup

<form method="post" name="myForm">.....</form>

Demo


HTML Code

<form method="post" onsubmit="return val()">
     <input type="text" id="username" name="username">       
     <button type="submit" >Sign Up</button>
 </form>

Javascript Code

function val(){

     var uname = document.getElementById('username').value;
     if(!uname){
         document.getElementById("error").innerHTML = "Enter a username";
         return false;
     }
     else{
         return true;
     }
}