2

So I want to fire a Javascript function every time a form 'submit' input is clicked, so I can handle the submission in Javascript.

I have the following:

$(':submit').click(function(){
    var currentForm = $(this)[0].form;
    event.preventDefault(); //Stop default form submission
    var formData = new FormData(currentForm);

    $.ajax({/*Handle form submission here*/});
});

I've tried a few different variations to get the currentForm, but for some reason it's always undefined?

Is this not the correct way to get a form object and then convert it to a FormData object in Javascript? I've tried several of the solutions on How to get the form parent of an input?, but none are working.

Any ideas?

0

1 Answer 1

5

you need to pass the event:

$(':submit').click(function(event){
   var currentForm = $('form')[0];
   event.preventDefault(); //Stop default form submission
   var formData = new FormData(currentForm);

   $.ajax({/*Handle form submission here*/});
});

UPDATE

So it appears $('form') returns a jQuery object, but an HTML element needs to be passed to FormData. [0] does that. It is the same as calling $('form').get(0). So use $('form')[0]

Sign up to request clarification or add additional context in comments.

1 Comment

It's hard to tell without seeing your actual code, but if you only have 1 form on the page and $('form')[0] works go for it.

Your Answer

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