2

I have a form I am trying to validate using JQuery Validate, which works fine. When the submit button is clicked, the submitHandler should 1. disable the button (to prevent multiple submissions) and 2. change the button text.

As is, the code works for validation but does not invoke the submitHandler.

I've looked over many threads on here, saying that the button must be type="submit", inside the <form> tags, etc. and cannot figure this out. The button is still able to be clicked multiple times.

Any help?

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>


<script type="text/javascript">


$(document).ready(function() {
  $("#freebottleform").validate({
     rules: {
       address : {
           required: true
       },
       city : {
           required: true
       },
       state : {
           required: true
       },
       zipcode : {
           required: true
       },
       phoneNumber : {
           required: true,
           phoneUS: true
       },
     },

     //Specify the validation error messages here
     messages: {
       email: {
         required: "Please enter email address",
        email: "Please enter a valid email address"
       },
       phoneNumber: {
         required : "Please enter your mobile number",
         digits: "Please enter digits only"
       }
     },
        submitHandler: function (form) {
            $("#finalSubmit").attr("disabled", true);
            $("#finalSubmit").html("Submitting... please wait.");
            form.submit();
        }

  });
});


</script>


<!DOCTYPE html>
<html lang="en">
<div class="freebottleform">

    <form method="post"  id="freebottleform" name="freebottleform" action="p6.php">
        Please enter your shipping details.<br>
        <br>
        Address:<br>
        <input type="text" name="address" class="required" placeholder="Please enter your address."/><br>
        <input type="text" name="address2" placeholder="Suite/Apt/Etc."/><br>
        <br>
        City:<br>
        <input type="text" name="city" class="required" placeholder="Please enter your city."/><br>
        <br>
        State:<br>
        <input type="text" name="state" class="required" placeholder="Please enter your state."/><br>
        <br>
        Zip Code:<br>
        <input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode."/><br>
        <br>
        Phone Number:<br>
        <input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number."/><br>
        <br>
        <label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
        <br>

    <button id="finalSubmit" type="submit" name="submit" value="final" >CONTINUE</button>

    </form>

</div>
</html>

matthias_h
  • 11,356
  • 9
  • 22
  • 40
  • A few questions: Have you tried upgrading to a newer version of JQuery, and have you seen the console output to see if there are any exceptions? – Dragonsnap Apr 28 '20 at 17:49
  • 1
    There is: `TypeError: $.validator.methods[method] is undefined`, seems to be caused by the rule `phoneUS`. – msg Apr 28 '20 at 17:56
  • @msg This was it! I previously had a method set in place for the phone number but left it in accidentally. Seems like it was catching that error then ignoring all code afterwards. Thank you so much! – Carlos Montero Apr 28 '20 at 18:32
  • @Dragonsnap Good catch, I was not aware I was running a very old version of JQuery and the Validation plugin. Updated both, but the problem persisted. Solved it with another answer. Thank you anyways! – Carlos Montero Apr 28 '20 at 18:33

3 Answers3

0

You can do your validation and disable the button on click event of button, at client side.

<script type="text/javascript">

$("#finalSubmit").click(function()
  {
   //do your validation and if correct then disable the button

    $("#finalSubmit").attr("disabled", true);

    //other work if any
   }
  );
</script>
Ashu_90
  • 904
  • 7
  • 8
0

1st of all instead of making validations with jQuery, make validations on server side like with PHP etc., and reflect the output on the display page.

An example here:

index.php

<!DOCTYPE html>
<html>
  <head>
    <title>Site Title</title>
  </head>
  <body>
    <h1>Form</h1>
    <div class="message"></div>
    <form method="post" action="" name="registrationForm">
      First Name <input type="text" name="fname"><br>
      Last Name <input type="text" name="lname"><br>
      Phone <input type="text" name="phone"><br>
      <input type="submit" value="Register" class="regbtn">
    </form>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script>
      $(document).ready(function(){
        $(".regbtn").click(function(){
          var form = document.registrationForm;
          var dataString = $(form).serialize();
          $.ajax({
            type: 'POST',
            url: "your-processing-page.php",
            data: dataString,
            cache: true,
            beforeSend: function(){
              $('.message').hide();
              $(".regbtn").prop('disabled', true).val('Please wait...');
            },
            success: function(data){
              $('.message').html(data).fadeIn();
              $(".regbtn").prop('disabled', false).val('Register');
            }
          });
          return false;
        });
      });
    </script>
  </body>
</html>

your-processing-page.php

<?php
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$lname = (!empty($_POST['lname']))?$_POST['lname']:null;
$phone = (!empty($_POST['phone']))?$_POST['phone']:null;

if($_POST){
  // Perform Checks Here
  if(trim($fname) == ''){
    echo "Please enter first name.";
  }else if(trim($lname) == ''){
    echo "Please enter last name.";
  }else if((strlen($phone)) == 0){
    echo "Please enter a phone number";
  }else if((strlen($phone)) < 10){
    echo "Phone number must not contain less than 10 digits.";
  }else if((strlen($phone)) > 10){
    echo "Phone number must not contain more than 10 digits.";
  }else{
    // If all checks are cleared perform your query
    $stmt = $pdo->prepare("INSERT INTO members(mem_fname, mem_lname, mem_phone)VALUS(:fname, :lname, :phone)");
    $stmt-> bindValue(':fname', $fname);
    $stmt-> bindValue(':lname', $lname);
    $stmt-> bindValue(':phone', $phone);
    $stmt-> execute();

    if($stmt){
      echo "Success! User has been registered.";
    }else{
      echo "Sorry, something went wrong. Please refresh the page and try again!";
    }
  }
}
?>

That's a complete answer. Here:

  1. Validation is done on server side using PHP (better method and must be followed).
  2. jQuery disables submit button to prevent double submission after click.
  3. jQuery changes button text value when submit button is pressed and changes back to default on successful return from form submission.

Note: The above is a fully working "standard" coding sample. That's how you should code. However, perform other necessary checks as per your need. Take the above coding only as a sample to frame your own code. Happy coding :)

0

Change the submit button name to something else because it overrides the submit() function on the form, then this code should work for you(Reference). ↓↓

$(document).ready(function() {
  $("#freebottleform").validate({
    rules: {
      address: {
        required: true
      },
      city: {
        required: true
      },
      state: {
        required: true
      },
      zipcode: {
        required: true
      },
      phoneNumber: {
        required: true,
        // phoneUS: true,
        digits: true
      },
    },

    //Specify the validation error messages here
    messages: {
      email: {
        required: "Please enter email address",
        email: "Please enter a valid email address"
      },
      phoneNumber: {
        required: "Please enter your mobile number",
        digits: "Please enter digits only"
      }
    },
    submitHandler: function(form) {
      $("#finalSubmit").attr("disabled", true);
      $("#finalSubmit").html("Submitting... please wait.");

      setTimeout(function() {
        form.submit();
      }, 3000);
    }

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>

</head>
<div class="freebottleform">

  <form method="post" id="freebottleform" name="freebottleform" action="p6.php">
    Please enter your shipping details.<br>
    <br> Address:
    <br>
    <input type="text" name="address" class="required" placeholder="Please enter your address." /><br>
    <input type="text" name="address2" placeholder="Suite/Apt/Etc." /><br>
    <br> City:
    <br>
    <input type="text" name="city" class="required" placeholder="Please enter your city." /><br>
    <br> State:
    <br>
    <input type="text" name="state" class="required" placeholder="Please enter your state." /><br>
    <br> Zip Code:<br>
    <input type="text" name="zipcode" class="required" placeholder="Please enter your zipcode." /><br>
    <br> Phone Number:<br>
    <input type="text" name="phoneNumber" class="required" placeholder="Please enter your phone number." /><br>
    <br>
    <label><input type="checkbox" name="subscribe" id="subscribe" value="true" checked/> Subscribe to our newsletter to get FREE weekly tips sent right to your inbox!</label><br>
    <br>

    <button id="finalSubmit" type="submit" name="save" value="final">CONTINUE</button>

  </form>

</div>

</html>
sauhardnc
  • 1,961
  • 2
  • 6
  • 16