user1049944
user1049944

Reputation:

jQuery: Prevent Form Submission on Button / Click Event

I'm using the following script in order to ensure that a <select> field has a value applied to it (other than the default) when the form is submitted.

// form-submit
$('#form-register form .button').click(function(e) {
  e.preventDefault();  // don't submit it
  var submitOK = true;
  $('#form-register').find("select").each(function() {
        if ($(this).val() == "Select Brand") {
              alert ('Please select an appliance and a brand');
              submitOK = false;
              return false;  // breaks out of the each
       }
  });
  if (submitOK) {
        $('#form-register form').submit();
  }
});

I had to bind the function to the click() event on the button because having it on the form's submit() event resulted in a 'too much recursion' error in my browser.

However now the problem I'm having is that the script can't seem to prevent the form from submitting, even if the validation error is alerted to the user.

Does anyone know how I can modify it to prevent the submission of the form in the event of a validation error?

I'm starting to think the fact I'm using Gravity Forms for WordPress it might be making things difficult. If it helps, here is the markup for the submit button (which includes some jQuery):

<input type="button" onclick="jQuery(&quot;#gform_target_page_number_1&quot;).val(&quot;2&quot;); jQuery(&quot;#gform_1&quot;).trigger(&quot;submit&quot;,[true]); " tabindex="13" value="Register My Appliances" class="button gform_next_button" id="gform_next_button_1_14">

Upvotes: 1

Views: 11841

Answers (1)

user1049944
user1049944

Reputation:

Fixed it! I rejigged my script like so and it seems to work nicely:

$('#form-register form').submit(function(e) {

        var error = 0;      
        $('#form-register').find("select").each(function() {
            if ($(this).val() == "Select Brand") {
                error ++;
                }
        });

        if (error > 0) {
            alert ('Please select an appliance and a brand');
            return false;
        }
    });

Upvotes: 3

Related Questions