Build JSON based on this requirement, can I use jQuery
I'm not sure how to write this JS, so ask for help here!
HTML
<div class="grid_18" id="reference_container">
<div class="grid_16">
<fieldset>
<legend>Website</legend>
<span class="grid_2">Person</span>
<input name="person" class = "grid_6" type="text" />
<span class="push_2">Year</span>
<input class="push_2" name="year" type="text" />
</fieldset>
</div>
<div class="grid_16">
&l开发者_如何学Got;fieldset>
<legend>Newspaper</legend>
<span class="grid_2">Author</span>
<input name="author" type="text" />
<span class="push_4">Year</span>
<input class="push_4" name="year" type="text" />
</fieldset>
</div>
</div>
What I need is a list of JSON one for each fieldset. The result will look like this:
[
{type:"website" , person: "(Based on user input)", year: "(Based on user input)"},
{type:"Newspaper", author: "(Based on user input)", year: "(Based on user input)" }
]
(type is static, the content comes from legend, other fields are not the same)
One thing need to notice is that the field name is not static(person, author etc..), need to pick up from name attribute.
This looks challenge for me, hope who can help with this~
var json = JSON.stringify($('fieldset').map(function () {
var self = $(this);
var obj = {
type: self.children('legend').text()
};
// Find each input element with a name attribute, and add the name/val to the object
self.find('input[name]').each(function () {
obj[this.name] = this.value + " (Based on user input)";
});
// Return the object we've constructed
return obj;
}).get());
map: Executes the provided function on each matched element, and returns a new jQuery object whose elements are the returned value of the function for each element.
get: Returns the jQuery object as an array.
Be sure to include the JSON library from https://github.com/douglascrockford/JSON-js, to support browsers which do not include the JSON library.
I have a solution that doesn't require json2.js. It uses jQuery's serialize()
method and replaces the query string characters with valid JSON delimiters instead:
var arr = [];
$("fieldset").each(function () {
var $this = $(this),
serialized = $this.children("input").serialize(),
type = $this.children("legend").text();
// Replace the jQuery-serialized content into valid JSON
serialized = serialized.replace(/([^=]+)=([^&]*)(&)?/g, function ($0, name, val, amp) {
return '"'+name+'":'+'"'+val+'"' + (amp ? "," : "");
});
// Add it to the array
arr.push('{"type":"'+type+'",'+serialized+'}');
});
// Join the array into a valid JSON string
var json = "[" + arr.join(",") + "]";
There's a working demo here: http://jsfiddle.net/AndyE/ASrKN/
Note that it doesn't re-decode the result (for instance, if the user input has characters that should be url-encoded), but you would probably want these to stay encoded if you're posting to the server anyway.
精彩评论