title: Excluding invisible form elements from FormData object
body: <p>I am using a combination of Javascript and jQuery to create a <code>FormData</code> object to send form data via AJAX request. This was my original code:</p>
  
  <pre><code>// $form is a jQuery object of the form in question
  var formData = new FormData($form[0]);
  </code></pre>
  
  <p>My problem is finding a concise way to exclude invisible (i.e. <code>.not(':visible')</code>) elements from the data collected by the <code>FormData</code> object. I know that I could easily do this using jQuery's <code>serialize()</code> method, but I need to use <code>FormData</code> in this particular instance due to the upload of image files.</p>
  
  <p>The only way I have managed to make this work is with the following code:</p>
  
  <pre><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);
  </code></pre>
  
  <p>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.</p>
  
  <p>I worry that using this method isn't very efficient. Is there a simpler way of achieving this?</p>