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?
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?
Share Improve this question edited May 23, 2017 at 11:50 CommunityBot 11 silver badge asked Jan 1, 2015 at 22:04 user3420034user3420034 01 Answer
Reset to default 5you 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]