serialArray testing
form to json
by toubia95
HTML
<h2>Form</h2>
<form action="" method="post">
<fieldset class="Dates">
Date1 : <input type="text" name="Dates" class="Dates" maxlength="12" size="12"/>
Age1 : <input type="text" name="Ages" class="Ages" maxlength="12" size="6"/> <br/>
</fieldset>
<fieldset class="Dates">
Date2 : <input type="text" name="Dates" class="Dates" maxlength="12" size="12"/>
Age2 : <input type="text" name="Ages" class="Ages" maxlength="12" size="6"/> <br/>
</fieldset>
<p><input type="submit" value="Serialiser"/></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>
CSS
body {
padding:10px;
}
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
/* http://www.json.org/js.html */
$.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() {
$('form').submit(function() {
var firstresult = $('form').serializeObject();
var myresult = JSON.stringify(firstresult);
$('#result').text(myresult);
$('#result').append(" Date2 = "+firstresult.Dates[1]);
return false;
});
});