Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventDefault not working with Zurb validation(Abide)

I am using zurb foundation for my website. It has got it's own validation. This is a link to the documentation.

I am using the following code to validate and submit my form data.

$('#myForm').on('valid', function (g) {
g.preventDefault();

//ajax call to insert the data

});

My problem is, I can't prevent the default submit of this form using preventDefault().

Any ideas how to do it?

I tried doing this.

 $('#myForm').on('valid submit', function (g) {
    g.preventDefault();

    //ajax call to insert the data

    });

This prevents the default submit, but it inserts the data twice.

like image 279
aBhijit Avatar asked Aug 07 '13 09:08

aBhijit


2 Answers

As stated in my comment on another answer:

This doesn't stop the "invalid" event from executing the AJAX, as "valid" and "invalid" are both triggered by "submit". The result is the above function is called by "submit", and even if the form is invalid, the AJAX call is made.

With a small modification, that code can work:

$("#myForm").on("valid invalid submit", function(g){
  g.stopPropagation();
  g.preventDefault();
  if (g.type === "valid"){
    // AJAX call
  }
});

This is a hacky way around the Abide validation events, but it'll work for me until the library provides better handling for this scenario.

--UPDATE--

The original question applied to Foundation 4. It looks like Foundation 5+ handles this scenario much better:

"To handle the submit event yourself, use data-abide="ajax" instead of data-abide inside the form tag."

<form data-abide="ajax">
  <div class="name-field">
    <label>Your name <small>required</small>
      <input type="text" name="users_name" required pattern="[a-zA-Z]+">
    </label>
    <small class="error">Name is required and must be a string.</small>
  </div>
  <button type="submit">Submit</button>
</form>
$('input[name="users_name"]').on('valid', function() {
  // Handle the submission of the form
});

i haven't used Abide since v4, so wasn't aware of this update.

like image 135
cautionbug Avatar answered Nov 02 '22 07:11

cautionbug


You can use g.stopPropagation() along with g.preventDefault(). It might help you fixing you rissue.

$('#myForm').on('valid submit', function (g) {
    g.stopPropagation();
    g.preventDefault();

    //ajax call to insert the data

});
like image 30
prava Avatar answered Nov 02 '22 08:11

prava