Reputation: 110
I have set of key-value in JSON format.
{
"name": "John",
"age": 23,
"address": "Lorem ipsum"
...
...
}
I need to create an editable form from this. The main challenge is that I have 100's of such key-value pairs in JSON format. The requirement is to resubmit the form using GET request. Only the fields that have been edited by user has to be submitted.
e.g. if an user makes an edit to "name" = "pete" and age = 24, I need to create a request with http://www.example.com/name=pete&age=24
Since the number of key-value pairs is very large, I cannot submit all the key-values to server every time an user edits some value.
Upvotes: 0
Views: 2032
Reputation: 12014
There are several libraries to do that. Also a simple way to get it, you can be:
function paramsToJSON(){
var search = location.search.substring(1), json_get;
try{
json_get = JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
}catch(e){}
return json_get || {};
}
var myJSON = {"name": "John", "age": 23, "address": "Lorem ipsum"};
var json = $.extend(myJSON, paramsToJSON()), changes = {};
$(document).ready(function(){
for(var key in json){
var element = $("<input>", {type: "text", name: key, value: json[key]});
var label = $("<label>").append(key).append(element);
element.bind("keyup change", function(){
changes[$(this).attr("name")] = $(this).val();
});
$("#fields").append(label)
}
$("#myForm").submit(function(e){
for(var x in json){
if(!changes.hasOwnProperty(x) || changes[x] == json[x]){
$("input[name='"+x+"']").prop("disabled", true)
}
}
});
})
label {display:block; text-transform: capitalize;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form id="myForm"></form><form id="myForm" method="get">
<div id="fields"></div>
<input type="submit" />
</form>
Upvotes: 1
Reputation: 537
buildForm = function(formJSON) {
for(var key in json) {
$("#myForm").append("<label name='"+key+"' >"+key+"</label>");
$("#myForm").append("<input type='text' name='"+key+"' value='"+value+"' >");
}
}
// if your json like this
var json = {
"name": "John",
"age": 23,
"address": "NY"
};
buildForm(json);
Upvotes: 0