Serialize Form Data To JavaScript Objects - serializeObject

File Size: 4.88 KB
Views Total: 8017
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Serialize Form Data To JavaScript Objects - serializeObject

The jQuery serializeObject plugin allows you to serializes form data to an object using serializeArray() method when submitting the form. It also supports file input that gets Base64 data strings using FileReader API.

How to use it:

1. Download and insert the jQuery serializeObject plugin along with the latest jQuery library into your html file.

<script src="https://code.jquery.com/jquery-3.2.1.min.js" 
        integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" 
        crossorigin="anonymous"></script>
<script src="jquery.serializeObject.js"></script>

2. The JavaScript to serializes your form data on submit.

<form>
  <p><input type="text" name="textinput" placeholder="" class="form-control"> input[name=<q>textinput</q>]</p>
  <p><label><input type="checkbox" name="chk_no_val"> :checkbox[name=<q>chk_no_val</q>]</label></p>
  <p><label><input type="checkbox" name="chk_value" value="the-value"> :checkbox[name=<q>chk_value</q>]</label></p>
  <p><input type="file" name="userfile" class="form-control" value="Choose A File"> input[name=<q>userfile</q>]</p>
  <p><input type="file" name="file_multiple" multiple class="form-control" value="Choose A File"> input[name=<q>file_multiple</q>]</p>
  <p><input type="submit" class="btn btn-danger" value="Submit"></p>
</form>
$(function(){
  $('form').on('submit', function(e){
    e.preventDefault();
    $(this).serializeObject().done(function(o){
      if(window.console) console.log(o);
      var j = JSON.stringify(o);
      alert(j);
      //window.open("data:image/png;base64," + o.userfile.data);
    });
  });
});

This awesome jQuery plugin is developed by Aleksandr-ru. For more Advanced Usages, please check the demo page or visit the official website.