Get all Form Values in JS Object via jQuery

Let’s consider a long form with 20 or 30 fields. There are times when you want to consume the data of such form directly as name => valuepairs as an object to either send it via Ajax or manipulate data in jQuery and so on. There is a neat little trick to achieve the same. Below is a small snippet which gets all the form values and converts it into a JavaScript Object using jQuery

JS Snippet

var data = {};
$(".form-selector").serializeArray().map(function(x){data[] = x.value;});
console.log(data) //Form values in object



$('.get-data').on('click', function(e) {
  var data = {}
  $(".form-selector").serializeArray().map(function(x) {
    data[] = x.value;
  console.log(data) //This shows the data in JS object
  $('.data-out').text(JSON.stringify(data)) //JS object is converted to string for demo


<form action="/" class="form-selector">
  First name:
  <input type="text" name="firstname" value="Mickey">
  <br> Last name:
  <input type="text" name="lastname" value="Mouse">
  <input type="submit" value="Submit" class="get-data">
<div class="data-out">

Level: Beginner

Technologies: JavaScript, jQuery

post via Codincafe