JSFiddle - React, Tailwind, and code Playground
by chridam
HTML
<form id="js-serialize">
<input name="para1" placeholder="String" />
<input name="para2" placeholder="Number" />
<input name="para3" placeholder="Boolean - true" />
<input name="para4" placeholder="Boolean - false"/>
<input type="submit" name="submit" />
</form>
JavaScript
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (this.value === 'true') {
this.value = (this.value === 'true');
}else if (this.value === 'false'){
this.value = (this.value === 'true');
} else if (!isNaN(this.value)) {
this.value = parseInt(this.value);
}
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function(){
$('form#js-serialize').on('submit', function(e){
e.preventDefault();
var $formData = $(this).serializeObject();
console.log($formData);
$.post('/echo/json', {
'data': $formData
}, function(data) {
console.log(data);
}, 'json');
});
});