Get all Form Values in JS Object via jQuery
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.name] = x.value;}); console.log(data) //Form values in object
JSFiddle
JavsScript
$('.get-data').on('click', function(e) {
e.preventDefault();
var data = {}
$(".form-selector").serializeArray().map(function(x) {
data[x.name] = 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
});
HTML
<form action="/" class="form-selector">
First name:
<br>
<input type="text" name="firstname" value="Mickey">
<br> Last name:
<br>
<input type="text" name="lastname" value="Mouse">
<br>
<br>
<input type="submit" value="Submit" class="get-data">
</form>
<div class="data-out">
</div>