最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - generate JSON data based on input fields - Stack Overflow

programmeradmin3浏览0评论

I would like to generate JSON data based on the following input fields: name uRL where the JSON data output would look something like this:

{   
"items": [
    {
        "url": "content/San-Francisco/berkeleyCampanile.jpg",
        "name": "Image 1 name"
    },
    {
        "url": "content/San-Francisco/castro.jpg",
        "name": "Image 2 name"
    },
    {
        "url": "content/San-Francisco/Tenderloin.jpg",
        "name": "Image 3 name"
    }
]
}

How it works right now is that theres two input field, name and url, and users can add another set of name and url inputs by clicking on the add button as shown on the picture

What I want is that when the user hits on generate it output based on all of the input filled the json data as shown on the format above.

Below is the code:

<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery/jquery-1.11.2.min.js"></script>
<script src="//code.jquery/jquery-migrate-1.2.1.min.js"></script>
</head>

<body>
<fieldset id="buildyourform">
    <legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />&nbsp;

<script>

$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
     var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
       var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");


        var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(name);
                fieldWrapper.append(url);

        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });

});

</script>

</body>

</html>

Any help will be greatly appreciated

Update:

<html>
<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery/jquery-1.11.2.min.js"></script>
<script src="//code.jquery/jquery-migrate-1.2.1.min.js"></script>
</head>

<body>
    <form id="myform">
<fieldset id="jsonBuilder">
    <legend id="legendHead">Neighboorhood Creation</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="generate" class="add">
</form>

<script>

 function showValues() {
 var frm = $('#myform');
 var data = JSON.stringify(frm.serializeArray());
}
</script>

<script>

$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
           var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");

        var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(name);
                fieldWrapper.append(url);

        fieldWrapper.append(removeButton);
        $("#jsonBuilder").append(fieldWrapper);
    });

});

</script>

</body>

</html>

I would like to generate JSON data based on the following input fields: name uRL where the JSON data output would look something like this:

{   
"items": [
    {
        "url": "content/San-Francisco/berkeleyCampanile.jpg",
        "name": "Image 1 name"
    },
    {
        "url": "content/San-Francisco/castro.jpg",
        "name": "Image 2 name"
    },
    {
        "url": "content/San-Francisco/Tenderloin.jpg",
        "name": "Image 3 name"
    }
]
}

How it works right now is that theres two input field, name and url, and users can add another set of name and url inputs by clicking on the add button as shown on the picture

What I want is that when the user hits on generate it output based on all of the input filled the json data as shown on the format above.

Below is the code:

<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery./jquery-1.11.2.min.js"></script>
<script src="//code.jquery./jquery-migrate-1.2.1.min.js"></script>
</head>

<body>
<fieldset id="buildyourform">
    <legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />&nbsp;

<script>

$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
     var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
       var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");


        var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(name);
                fieldWrapper.append(url);

        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });

});

</script>

</body>

</html>

Any help will be greatly appreciated

Update:

<html>
<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery./jquery-1.11.2.min.js"></script>
<script src="//code.jquery./jquery-migrate-1.2.1.min.js"></script>
</head>

<body>
    <form id="myform">
<fieldset id="jsonBuilder">
    <legend id="legendHead">Neighboorhood Creation</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="generate" class="add">
</form>

<script>

 function showValues() {
 var frm = $('#myform');
 var data = JSON.stringify(frm.serializeArray());
}
</script>

<script>

$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
           var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");

        var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(name);
                fieldWrapper.append(url);

        fieldWrapper.append(removeButton);
        $("#jsonBuilder").append(fieldWrapper);
    });

});

</script>

</body>

</html>
Share Improve this question edited Mar 11, 2015 at 12:36 asked Mar 11, 2015 at 12:07 user4644565user4644565 3
  • If possible add id to your input filed also – Pranay Rana Commented Mar 11, 2015 at 12:14
  • allow me to clarify. My question is I have a set of inputs, how do I convert them into JSON data. where I have a group set of inputs (name, url), and I want each pair to be output as a json data all together and displayed to the user. AN example of a json data being output is here jsfiddle/sxGtM/3 but this is based on a html form, I don't have a form just inputs – user4644565 Commented Mar 11, 2015 at 12:15
  • 2 As suggested, I have added an ID to each input, known as name and url respectively – user4644565 Commented Mar 11, 2015 at 12:19
Add a ment  | 

5 Answers 5

Reset to default 2

A suggestion:

  1. same ids are getting repeated so i changed it to class.

All you need is this:

  $('#preview').click(function(){
    var o = {"items":[]}; // create an object with key items to hold array
    $('.fieldwrapper').each(function(){ // loop in to the input's wrapper
      var obj = {
        url :  $(this).find('.url').val(), // place the url in a new object
        name : $(this).find('.name').val() // place the name in a new object
      };
      o.items.push(obj); // push in the "o" object created
    });
    $('#console').text(JSON.stringify(o)); // strigify to show
  });

$(document).ready(function() {
  $("#add").click(function() {
    var intId = $("#buildyourform div").length + 1;
    var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
    var name = $("<input type=\"text\" \" placeholder=\"Name of Neighborhood\"class=\"name fieldname\" />");
    var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"url fieldname\" />");


    var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
    removeButton.click(function() {
      $(this).parent().remove();
    });
    fieldWrapper.append(name);
    fieldWrapper.append(url);

    fieldWrapper.append(removeButton);
    $("#buildyourform").append(fieldWrapper);
  });
  
  $('#preview').click(function(){
  
    var o = {"items":[]}; // create an object with key items to hold array
    
    $('.fieldwrapper').each(function(){ // loop in to the input's wrapper
      var obj = {
        url :  $(this).find('.url').val(), // place the url in a new object
        name : $(this).find('.name').val() // place the name in a new object
      };
        o.items.push(obj); // push in the "o" object created
    });
    
    $('#console').text(JSON.stringify(o)); // strigify to show
    
  });
  

});
#console {
  background: #c5c5c5;
  height: 50px;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<fieldset id="buildyourform">
  <legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />&nbsp;
<div id='console'></div>

I have made a JSFiddle for your guidance. Please take a look.

JSFiddle

$( "form" ).submit(function( event ) {
    var items = {};
  items["items"] = $( this ).serializeArray();
    console.log(JSON.stringify(items));
  event.preventDefault();
});
<form>
<input type="text" name="url" />
<input type="text" name="image" />
<input type="text" name="url" />
<input type="text" name="image" />
    <button class="generate" type="submit" id="generate">Generate</button>
</form>

You can use the JQuery .serializeArray() method, here's the documentation Here's an example:

var json = $('#form').serializeArray();

If you don't want to add the form tag to your code, here's a script that creates the JSON from your current form, FIDDLE

$(document).ready(function() {
$("#add").click(function() {
    var intId = $("#buildyourform div").length + 1;
    var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
    var name = $("<input type=\"text\" placeholder=\"Name of Neighborhood\"class=\"fieldname\" name=\"name\" />");
       var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" name=\"url\" />");

    var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
    removeButton.click(function() {
        $(this).parent().remove();
    });
    fieldWrapper.append(name);
            fieldWrapper.append(url);

    fieldWrapper.append(removeButton);
    $("#buildyourform").append(fieldWrapper);
});
$('#preview').click(function(){
    var json = {};
    json.items = [];
    $('.fieldwrapper').each(function(e){
        var obj = {};
        obj.name = $(this).find('input[name=name]').val();
        obj.url = $(this).find('input[name=url]').val();
        json.items.push(obj);            
    });

    console.log(json);
});


});

Here is another one without the form demo@fiddle

$("#preview").click(function() {
    var arr = {};
    arr.items = [];

    $(".fieldwrapper").each(function() {
        var entry = {}
        var neighborhood = $(this).find("input[name='neighborhood']").val();            
        var url = $(this).find("input[name='url']").val();
        entry["url"] = url;
        entry["name"] = neighborhood;
        arr.items.push(entry);
    });
    alert (JSON.stringify(arr, null, 4));
});

P.S. I have added name attributes to your input elements.

With Json Indentation

html

<fieldset id="buildyourform">
    <legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />&nbsp;
<pre id="json"></pre>

Javascript

var items = {'items':[]}
$(document).ready(function() {
    $("#add").click(function() {
        var intId = $("#buildyourform div").length + 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
     var name = $("<input type=\"text\" \"class=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
       var url = $("<input type=\"text\"class=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");


        var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(name);
                fieldWrapper.append(url);

        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $('#preview').on('click',function(){
        $('.fieldwrapper').each(function(){
            items.items.push({'url':$(this).find('.url').val(),'name':$(this).find('.fieldname').val()});
});
document.getElementById("json").innerHTML = JSON.stringify(items, undefined, 2);
    });
});

here is a Fiddle

发布评论

评论列表(0)

  1. 暂无评论