You are viewing limited content. For full access, please sign in.

Question

Question

Process Submit Event Function Only if Submit Processes Fully

asked on January 5, 2017 Show version history

I have a function that is called when the user clicks the Submit button.  It updates a field value that I'm using to track when the submit occurred.

$(".action-btn.Submit").on('click', function() {
  //steps of the function go here
});

This works to call the function, unfortunately, it processes the function every time the button is clicked, regardless of whether the submit actually processes or not.  For instance, if required fields are missing, it will still process this function.  That's not what I want to occur.

Does anyone know a way to limit processing of the function to only when the submit is successful?

0 0

Answer

SELECTED ANSWER
replied on January 6, 2017 Show version history

Hi Matthew,

There are a couple of considerations:

  1. The validation of fields occurs after the form "submit" event is registered.
  2. The field needs to be updated before the form is fully submitted, anyway.

The best way I've found so far is to do some basic validation on my own in the function handler for the Submit button "click" event:

$(document).ready(function() {
  $('form.cf-form').on('submit', function() {
    var noErrors = true;
    // check that all required fields are nonempty
    $('*[required]').each(function() {
      if ($(this).val() == '') noErrors = false;
    });
    // check that any (required) fields with regex patterns match
    $('*[pattern]').each(function() {
      // prepending /^.{0}$|/ to the pattern allows for blank values;
      //   note that any empty required fields of this type will be
      //   handled in the step above
      var patternString = '^.{0}$|' + $(this).attr('pattern');
      var pattern = new RegExp(patternString);
      if (!pattern.test($(this).val())) noErrors = false;
    });
    if (noErrors) $('.fillOnSubmit input').val('Hello');
  });
});

where there is a single-line input with class ".fillOnSubmit" that gets populated with "Hello" if all goes according to plan.

I'm not sure if I missed some other kind of validation, but this might serve your purposes?

Hope this helps!

1 0
replied on January 6, 2017

Worked!  Thanks @████████!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.