根据输入字段生成JSON数据

时间:2015-03-11 12:07:30

标签: javascript jquery html json html5

我想基于以下输入字段生成JSON数据: 名称 网址 JSON数据输出看起来像这样:

{   
"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"
    }
]
}

现在如何工作是两个输入字段,名称和网址,用户可以通过点击图片上显示的添加按钮添加另一组名称和网址输入

enter image description here

我想要的是当用户点击时根据填充json数据的所有输入生成输出,如上面的格式所示。

以下是代码:

<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/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>

非常感谢任何帮助

更新

<html>
<head>

      <link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/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>

5 个答案:

答案 0 :(得分:3)

建议:

  1. 相同的ID正在重复,所以我把它改成了课程。
  2. 所有你需要的是:

      $('#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
      });
    

    &#13;
    &#13;
    $(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
        
      });
      
    
    });
    &#13;
    #console {
      background: #c5c5c5;
      height: 50px;
    }
    &#13;
    <script src="https://ajax.googleapis.com/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>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

你可以使用JQuery .serializeArray()方法,这里是documentation 这是一个例子:

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

如果您不想在代码中添加表单标记,可以使用以下格式创建JSON的脚本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);
});


});

答案 2 :(得分:1)

我已经为你的指导做了一个JSFiddle。请看一下。

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>

答案 3 :(得分:1)

使用Json缩进

<强> 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);
    });
});

这是一个Fiddle

答案 4 :(得分:0)

这是另一个没有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。我在输入元素中添加了名称属性。

相关问题