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?
As @anthonyGist has pointed out in the comments, set invisible elements to disabled:
$(':hidden').prop('disabled', true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With