1

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">
3
  • Consider using form 'onsubmit' handler instead ( As you did it before ) It is simply impossible to cancel form submission from "onclick" button handler. Commented Dec 22, 2013 at 15:01
  • You could see on this test page, that "click" handler can't cancel form submission - jsbin.com/iDuYefed/1/edit Commented Dec 22, 2013 at 15:10
  • Thanks however if I run the function on the form submission, then I get a 'too much recursion' error because there is a '.submit()' event triggered in the function itself. Is that what you meant? Commented Dec 22, 2013 at 15:28

1 Answer 1

3

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;
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.