Skip to content

Instantly share code, notes, and snippets.

@stl-od
Created April 19, 2012 07:36
Show Gist options
  • Save stl-od/2419436 to your computer and use it in GitHub Desktop.
Save stl-od/2419436 to your computer and use it in GitHub Desktop.
An offline form experiment
$.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() {
formData = JSON.stringify($('form').serializeObject());
$('#result').text(formData);
return false;
});
});
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h2>Form</h2>
</div>
<div data-role="content">
<form action="" method="post">
<label for="Fname">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/>
</label>
<label for="Lname">
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/>
</label>
<fieldset data-role="controlgroup">
<legend>Gender:</legend>
<label>
<input type="radio" name="gender" value="Male"/>Male:
</label>
<label>
<input type="radio" name="gender" value="Female"/>Female:
</label>
</fieldset>
<fieldset data-role="controlgroup">
<legend>Favorite Food:</legend>
<label><input type="checkbox" name="food[]" value="Steak"/>Steak:</label>
<label><input type="checkbox" name="food[]" value="Pizza"/>Pizza:</label>
<label><input type="checkbox" name="food[]" value="Chicken"/>Chicken:</label>
</fieldset>
Select a Level of Education:
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
<input type="submit" value="Submit" data-theme="a" />
</form>
<h2>JSON</h2>
<pre id="result">
</pre>​​​​​
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment