Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a hash into a form input?

Say I have a hash and I want to enter it as a val()

$("#form_attribute").val( hash )

It gets stored as a string "[Object, object]"

How do I keep it as a hash and then allow the form to send this hash to my server?

like image 295
Trip Avatar asked Dec 11 '22 19:12

Trip


2 Answers

If you want to convert an object/value to a JSON string, you could use JSON.stringify to do something like this:

$("#form_attribute").val(JSON.stringify(hash))

This is a built-in method to most recent browsers that converts an object to JSON notation representing it. If a certain browser doesn't support it, there are several polyfills to include on your page to provide support


References:

  • JSON.stringify - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
  • window.JSON browser compatibility - http://caniuse.com/json
  • JSON3 polyfill - http://bestiejs.github.com/json3/
  • JSON2 polyfill - https://github.com/douglascrockford/JSON-js
  • JSON2 vs JSON3 - JSON polyfill: JSON 2 or JSON 3?
like image 179
Ian Avatar answered Dec 27 '22 23:12

Ian


You can store it as a JSON string:

$('#form_attribute').val(JSON.stringify(hash));

Or you can store your original object in a data attribute:

$('#form_attribute').data('hash', hash);
like image 37
Blender Avatar answered Dec 28 '22 01:12

Blender