Converting all form elements into a Hash $H(e)
Create a form with an id attribute, then input fields as normal, with names.
The form elements must have a name attribute (id not required).
Hash to JSON:
The quick and dirty: onclick="$('hash_to_json').update($H($('form_name').serialize(true)).toJSON());"
The detailed steps:
var hash_form = $('form_name').serialize(true);
But it doesn't behave as expected, so don't rely on Object:
Use $H(element_name) to access it as a Prototype Hash.
var h = $H(hash_form);
var json = h.toJSON();
Debugging
var hash_foo = new Hash();
hash_foo.set('name', 'Sample hash');
hash_foo.set('int', 12);
Output:
Get the contents of a hash file:
$H(hash_foo).inspect(); // returns #<Hash:{'name': 'Sample hash'}>
inspect() is prefixed by a # and enclosed in < > so it won't be displayed properly if you are just viewing HTML. It's going to be simpler to just dump it to a JSON string and display it that way.
$H(hash_foo).toJSON(); // returns {"name": "Sample hash"}
Serializing Form Gotchas
Form with id of 'simple'.
String:
To serialize a form (get all the elements into a Hash), use $(e).serialize(true);
According to the docs, this is is a Hash object, but you cannot treat it as such. Running Hash functions on it will silently fail.
var json_hash = $('simple').serialize(true);
var json_str = $H(json_hash).toJSON(); // returns string: {"text": "Simple form text"}
json_hash.set('key', 'value'); // Error: json_hash.set is not a function
So, the gotcha is that serialize() returns an object in a class all it's own. It's not a Hash in the Prototype sense, and you can run some functions on it, but not all.