Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding invisible form elements from FormData object

I am using a combination of Javascript and jQuery to create a FormData object to send form data via 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 (i.e. .not(':visible')) elements from the data collected by the FormData object. I know that I could easily do this using jQuery's serialize() method, but I need to use FormData in this particular instance due to the upload of image files.

The only way I have managed 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 simply remove invisible elements from the clone and pass that to FormData, as none of the clone is visible unless I attach it to the DOM so all data elements are removed. So, my only solution was to clone the original form, and reserve the clone to re-attach to the DOM after removal of invisible elements from the original form.

I worry that using this method isn't very efficient. Is there a simpler way of achieving this?

like image 501
Maccath Avatar asked Oct 16 '14 13:10

Maccath


1 Answers

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

$(':hidden').prop('disabled', true);
like image 155
PeterKA Avatar answered Sep 29 '22 00:09

PeterKA