使用 JSON 数组填充输入字段

Filling input fields with a JSON Array

本文关键字:输入 字段 填充 数组 JSON 使用      更新时间:2023-09-26

找了大约一个小时后,我找不到任何人分享了他们从 JSON 数组中用相应值填充 HTML 页面上输入字段的方式。

例如,输入框的名称是数组的第一个元素,那么应该进入其中的值是第二个元素。

更多例子:

输入表格如下...

<input type="text" id="123111" data-inline="true" class="firstclass" name="xx3111" data-theme="b" style="color: red;">

JSON 数组为:

000001: "firstValue"
000002: "secondValue"
000003: "thirdValue"
000004: "fourthValue"
etc, etc

我想做的是用数组中的值填充相应的输入框。再比如:

ID 000123 的输入由数组中具有数字 000123 的字符串填充

<input type="text" id="000001">用字符串 first 值填充

您需要遍历数据对象的每个属性并选择相应的输入元素,然后设置其值:

for (var key in data) {
    document.getElementById(key).value = data[key];
} 

data是您称为"JSON 数组"的对象。

$.each(json, function(index, value) {
    $('input#' + index).val(value);
});

B/c我很懒,我只是使用了jQuery。这个概念与您使用纯 js 或其他库(如 underscore)的天气相同。我假设您的 JSON 数组是有效的,而您只是错误地显示它。

如果要按id选择DOM元素(在本例中为输入字段),并且不能100%确定ID是否存在,则需要检查nullundefined

JSFIDDLE 演示

var mydata ={
    "000001": "firstValue",
    "000002": "secondValue",
    "000003": "thirdValue",
    "000000": "This id does not exist",
    "000004": "fourthValue"
}

for (var k in mydata) {
      var input = document.getElementById(k);
      if(typeof input !== 'undefined' && input !== null) {//skip non exixting ids
        input.value= mydata[k];
      }
} 
// Make one input field, based on value and id
function makeField(value, id) {
    var input = document.createElement('input');
    input = document.createElement('input');
    input.id = id;
    input.className = 'firstclass';
    input.type = 'text';
    input.setAttribute('data-inline', "true");
    input.setAttribute('data-inline', "true");
    input.setAttribute('data-theme', "b");
    input.setAttribute('style', "color:red;");
    input.setAttribute('value', value);
    return input;
}
// Make many fields, from an object.
function makeInputsFromObject(obj) {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        fragment = document.createDocumentFragment(),
        id,
        input;
    for (id in obj) {
        if (hasOwnProperty.call(obj, id)) {
            fragment.appendChild(makeField(obj[id], id));
        }
    }
    return fragment;
}
// Make many fields, from an array.
function makeInputsFromArray(arr) {
    return arr.reduce(
        function (fragment, value, id) {
            fragment.appendChild(makeField(value, id));
            return fragment;
        },
        document.createDocumentFragment()
    );
}
// Test/demonstration code below.
document.body.appendChild(
    makeInputsFromObject({
        "000001": "firstValue",
        "000002": "secondValue",
        "000003": "thirdValue",
        "000004": "fourthValue"
    })
);
document.body.appendChild(
    makeInputsFromArray([
        "fifthValue",
        "sixthValue",
        "seventhValue",
        "eighthValue"
    ])
);

如测试/演示代码所示,您将数据结构提供给其中一个makeInputs函数(以合适的为准),该函数将返回一个DOM节点(实际上是DocumentFragment)。以通常的方式将其添加到 DOM 中,它会为您提供您的字段。

正如 Array 版本所强调的那样,如果您实际使用 Array,则可以将其实现为 reduce() 操作。对象没有内置的类似 reduce() 的函数,所以我们即兴发挥,但一般原理是相同的,我们甚至可以使用相同的 makeField() 函数。

请注意:这两个版本都没有将内容定制到您想要的程度。数组版本不能完全正确执行 ID,并且这两个版本都不完全匹配您的 name 属性方案。但我希望这能说明这个原则。

您正在寻找使用相应值从 JSON 数组填充 HTML 页面上的输入字段。

  1. 首先获取 javascript 函数中的输出值。
  2. 然后使用 $.each 函数遍历 json 数组,如下所示。
  3. 然后再次遍历 HTML 函数中的输入字段。
  4. 如果 json 数组中的数组键与 id 匹配,请将 json 值作为输入值放在那里。

我试图用以下方式粗略地说明它:

<?php
            $.ajax({
                url : path/to/json/output/file,
                type : 'POST', //the way you want to send data to your URL
                dataType : 'json',
                error: function(){
                        $('#result_table_json').append('<p>Error Loading Data</p>');
                        },
                success :function(response){
                //get the array element one by one in the following loop
                    $.each(row,function(key,value){
                        //now check for the right input id that matches the key. I guess all your inputs have something in common eg. class name. So loop through the fields
                        $.each(".firstclass")function(){
                            if( $( this ).attr( 'id' ) === key )
                            {   //fill the input field here 
                                $(this).val(value);                                         }
                            //Alternatively you may append the fields externally in case they dont exist without the json values like this:
                            //$('#result_table_json').append('<input type="text" id="'+key+'" data-inline="true" class="firstclass" name="'+key+'" data-theme="b" value="'+value+'" style="color: red;">');
                        });     
                    });

                }
            });
    ?>