Serialize Form Data to Json
HTML
<h2>Form</h2>
<form class="multi-legends">
<input type="radio" name="checked" value=""/>
<input type="text" name="descrpL" maxlength="12" size="12"/> <br/>
<br/>
<p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>
CSS
form {
line-height: 2em;
}
p {
margin: 5px 0;
}
h2 {
margin: 10px 0;
font-size: 1.2em;
font-weight: bold
}
#result {
margin: 10px;
background: #eee;
padding: 10px;
height: 40px;
overflow: auto;
}
JavaScript
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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() {
$('.multi-legends').submit(function() {
$('#result').text(JSON.stringify($('.multi-legends').serializeObject()));
return false;
});
});