最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get form & FormData objects from input element? - Stack Overflow

programmeradmin5浏览0评论

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 0
Add a ment  | 

1 Answer 1

Reset to default 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]

发布评论

评论列表(0)

  1. 暂无评论