How to redirect thank-you page after form validate in jQuery

Viewed 42

I need to redirect to thank you page after the valid submit a form, my form show the thank you page in both conditions, valid and invalid.

Can anyone help me with this?

$(document).ready(function() {

        // Attach the event handler for the keyboard keyup
        $('.my-input').keyup(function() {
            $(".error").hide();
            var hasError = false;
            var nameReg = /^([a-zA-Z_ ]{0,50})$/g;
            var nameaddressVal = $(".my-input").val()

            if (nameaddressVal == "") {
                $(".my-input").after(
                    '<span class="error text-danger">Please enter your name.</span>'
                );
                hasError = true;
            } else if (!nameReg.test(nameaddressVal)) {
                $(".my-input").after(
                    '<span class="error text-danger">Allowed: aA</span>'
                );
                hasError = true;
            }
            $('input[type=submit]').click(function() {
                if (hasError == true) {
                    return false;
                } else  if (nameReg.test(nameaddressVal)) {
                    window.location.replace("thank_you.php");
                }
                else{
                    return false;
                }
            });
        });
    });
1 Answers

The issue is that you are defining all your vars and attaching your submit event handler within your keyup handler - and as such hasError is always false.

To fix move your hasError var and submit handler out of that method and into the scope of your ready function.

Also - there is no need to test "if(x == true)" if x is a boolean (true/false) - you can just do "if(x)". Also your else if conditions are redundant.

Here you go, I tided it up for you - this should work.

e.g.

$(document).ready(function() {
  var hasError = false; // this scope so it is accessible in the click handler
  var nameReg = /^([a-zA-Z_ ]{0,50})$/g;

  // Attach the event handler for the keyboard keyup
  $('.my-input').keyup(function() {

    var nameaddressVal = $(".my-input").val();
    $(".error").hide();
    hasError = false;

    if ("" === nameaddressVal) {
      $(".my-input").after(
        '<span class="error text-danger">Please enter your name.</span>'
      );
      hasError = true;
    }

    if (!nameReg.test(nameaddressVal)) {
      $(".my-input").after(
        '<span class="error text-danger">Allowed: aA</span>'
      );
      hasError = true;
    }
  });
        
  // Attach the event handler for submit
  $('input[type=submit]').click(function() {
    if (hasError) {
      return false;
    }

    window.location.replace("thank_you.php");
  });
});
Related