Excluding invisible form elements from the FormData object

I am using a combination of Javascript and jQuery to create an object FormData

to submit form data via an AJAX request. This was my original code:

// $form is a jQuery object of the form in question
var formData = new FormData($form[0]);

      

My problem is finding a concise way to exclude invisible elements (i.e. .not(':visible')

) from the data collected by the object FormData

. I know I could easily do this with jQuery method serialize()

, but I need to use FormData

on this particular instance due to image files loading.

The only way I was able to make this work is with the following code:

// $form is a jQuery object of the form in question
// Clone the original form
var $formClone = $form.clone();

// Remove invisible items from form
$form.find('input, textarea').not(':visible').remove();

// Collect form data with invisible items removed
var formData = new FormData($form[0]);

// Replace form with cloned form which retains invisible elements
$form.replaceWith($formClone);

      

I can't just remove the invisible elements from the clone and pass that to FormData as none of the clones show up unless I attach it to the DOM, so all data elements are removed. So, the only solution was to clone the original form and reserve the clone to reattach to the DOM after removing invisible elements from the original form.

I am worried that using this method is not very efficient. Is there an easier way to achieve this?

+3


source to share


1 answer


As @anthonyGist pointed out in the comments, set disabled invisible elements:



$(':hidden').prop('disabled', true);

      

+2


source







All Articles