I am building a dynamic form creator that allows users to add form elements and change the properties. I need to find a way to store this data on the client side without the complexity of XML or JSON. The user could add 50 form elements from text box to radio to textarea. Each element has a different number of changeable variables.
I am currently storing them in hidden fields values like:
type:text, size:30, required:yes, top:30, left:30
type:textarea, cols:30, rows:5, top:50, left:60
I am using jquery to add each item and the hidden.
var typeVariable = 'type:input';
var startPosLeft = 'left:' + Math.round($(newElem).offset().left$('.container').offset().left);
var startPosTop = 'top:' + Math.round($(newElem).offset().top - $('.container').offset().top);
var newElemValue = typeVariable + ',' + startPosTop + ',' + startPosLeft;
// creates hidden form elements to store data
$('<input>').attr({'type': 'text', value:newElemValue, 'name':'hidden' + newNumDivs, id:'hID' + newNumDivs}).appendTo('.hiddenDiv');
-
Is this the best way to store and retrieve data without doing a ton of ajax calls
-
How can I call a specific element from a string like:
type:text, size:30, required:yes, top:30, left:30
I will need ‘text’ not ‘type:text’ .
How can I update a specific element in this string? If size:30 changes to size:50 how do I change this data stored in a hidden field and insert it into
type:text, size:50, required:yes, top:30, left:30
You should be storing all of that information in a JavaScript array, where each element in the array is an object with the appropriate properties to represent one of the form elements your user is creating. You can easily add elements and update properties of existing items.
When your user is ready to submit you can serialise the array to JSON and submit in a conventional form field or via Ajax.
UPDATE prompted by your latest comment. To “name the array elements” you use an object instead of an array:
Or you can define them all in a single statement (note the nested curly braces):
Then to get, say, the “top” property for a “textareaTemplate” you say:
To loop through all items in the object say:
For more information see https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects.