javascriptjqueryhtmlforms

Show error on form submit


I want to show an error using jQuery, there is no error checking yet, but I just want to learn more about jQuery and it seems like I can't get this working.

So, I want to show the error anyway when the submit button is pressed. I tried, to set visibility using jquery to visible onclick and invisible beforehand but it didn't work. It showed for a quick second and then it dissapeared. How can I make it show there until next submit buttonpress?

<form id="quick-register" action="">
    Username: <input type="text" name="quick-username"> <br>
    <span id="quick-user-wrong">Wrong Username (a-z, A-Z, 0-9)</span>

    Password: <input type="password" name="quick-password"> <br>
    <span id="quick-pass-wrong">Wrong Password</span>

    Repeat Password: <input type="password" name="quick-password2"> <br>
    <span id="quick-pass2-wrong">Password doesn't match</span>

    E-mail: <input type="email" name="quick-email"> <br>
    <span id="quick-email-wrong">Invalid E-mail Address</span>

    <button id="quick-submit">Register</button>
</form>

jQuery

$(function () {
    $("#quick-submit").one("click", function () {
        $("#quick-user-wrong").css("visibility", "visible");
    });
});

Solution

  • You can create an event listener that will trigger on form submission, which you can cancel and submit at a later time.

    $( "#quick-register" ).submit(function( e ) {
      //cancel submission
      e.preventDefault();
    
      // .... your error handling/etc ...
      
      if(noerror){
        //submit form later
        $(this).unbind("submit").submit();
      }
    
    });
    

    The problem at the moment is that the form is being submitted. This causes the page to refresh, which is why you only see your javascript work for a brief second.