如何基于JSON响应数据添加HTML表单字段

时间:2018-06-25 13:15:23

标签: javascript php json

我有一个用于产品的HTML表单,该表单最初包含2行的字段组(用于产品组件),并且可以使用带有onClick事件的按钮向js函数addRow()添加行。代码是:

<?php
                $arrayNumber = 0;
                for($x = 1; $x < 3; $x++) { ?>
                    <tr id="editRow<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">                          
                        <td style="padding-left:20px;padding-right: 20px;">
                            <div class="form-group">
                            <select class="form-control" name="editRawName[]" id="editRawName<?php echo $x; ?>" onchange="getRawData(<?php echo $x; ?>)">
                                <option value="">~~SELECT~~</option>
                                <?php
                                    $rawSql = "SELECT * FROM raw_material WHERE status = 1";
                                    $rawData = $connect->query($rawSql);

                                    while($row = $rawData->fetch_array()) {                                         
                                        echo "<option value='".$row['raw_id']."' id='changeRaw".$row['raw_id']."'>".$row['raw_name']."</option>";
                                        } // /while 

                                ?>
                            </select>
                            </div>
                        </td>
                        <td style="padding-left:20px;">
                            <div class="form-group">
                            <input type="number" name="editQuantity[]" id="editQuantity<?php echo $x; ?>"  autocomplete="off" class="form-control" min="1"/>
                            </div>
                        </td>
                        <td>

                            <button class="btn btn-default removeRawRowBtn" type="button" id="removeRawRowBtn" onclick="removeRawRow(<?php echo $x; ?>)"><i class="glyphicon glyphicon-trash"></i></button>
                        </td>
                    </tr>
                <?php
                $arrayNumber++;
                } // /for?>

现在,要编辑产品,我使用js函数editProduct()来获取所选的产品数据,并将其作为JSON响应返回,以填写产品表单字段。抓取并填写产品字段的editProduct功能代码部分为:

function editProduct(productId = null) {

if(productId) {
    $("#productId").remove();
    $(".text-danger").remove();
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $('.div-loading').removeClass('div-hide');
    $('.div-result').addClass('div-hide');

    $.ajax({
        url: 'action.php',
        type: 'post',
        data: {productId: productId},
        dataType: 'json',
        success:function(response) {
            $('.div-loading').addClass('div-hide');
            $('.div-result').removeClass('div-hide');

            $(".editProductFooter").append('<input type="hidden" name="productId" id="productId" value="'+response.product_id+'" />');

            // product name
            $("#editProductName").val(response.product_name);
            // category name
            $("#editCategoryName").val(response.categories_id);
            // quantity
            $("#editProductQuantity").val(response.quantity);
            // product unit
            $("#editProductUnit").val(response.product_unit);
            // sales margin
            $("#editSalesMargin").val(response.sales_margin);
            // status
            $("#editProductStatus").val(response.status);
            // Get the product components count
            var totalComponents = response.total_components;
            // Loop for every component
            // Set the fields id that will contains the data
            // Fill the fields with data
            for (var x = 0; x<totalComponents; x++){

                var idrawn = "#editRawName"+x.toString();
                var idrawq = "#editQuantity"+x.toString();
                var resri = "raw_id_"+x.toString();
                var resqu = "rp_quantity_"+x.toString();
            $(idrawn).val(response[resri]);
            $(idrawq).val(response[resqu]);
            }

问题是:如果产品的组件总数超过2,则需要添加行以填充组件数据。 首先,我试图在editProduct函数中的最后一个for循环之前启动addRow()函数,如下所示(无效):

if (totalComponents > 2) {
                var adro = totalComponents - 2;
                for (var y=0; y<adro; y++)
                { addRow(); }
            }

然后,我尝试使用此处发布的解决方案来模拟单击添加组件按钮以启动addRow函数的行为:How to simulate a click with JavaScript?并按如下所示更改上面的代码:

if (totalComponents > 2) {
                var adro = totalComponents - 2;
                for (var y=0; y<adro; y++)
                { eventFire(document.getElementById('addRowBtn'), 'click'); }
            }

但仍然没有运气。 addRow函数的代码为:

function addRow() {
$("#addRowBtn").button("loading");
var tableLength = $("#rawTable tbody tr").length;
var tableRow;
var arrayNumber;
var count;

if(tableLength > 0) {
    tableRow = $("#rawTable tbody tr:last").attr('id');
    arrayNumber = $("#rawTable tbody tr:last").attr('class');
    count = tableRow.substring(3);
    count = Number(count) + 1;
    arrayNumber = Number(arrayNumber) + 1;
} else {
    // no table row
    count = 1;
    arrayNumber = 0;
}

$.ajax({
    url: 'action1.php',
    type: 'post',
    dataType: 'json',
    success:function(response) {
        $("#addRowBtn").button("reset");
        var tr = '<tr id="row'+count+'" class="'+arrayNumber+'">'+
            '<td style="padding-left:20px;padding-right: 20px;">'+
                '<div class="form-group">'+

                '<select class="form-control" name="rawName[]" id="rawName'+count+'" onchange="getRawData('+count+')" >'+
                    '<option value="">~~SELECT~~</option>';
                    $.each(response, function(index, value) {
                        tr += '<option value="'+value[0]+'">'+value[1]+'</option>';
                    });
                tr += '</select>'+
                '</div>'+
            '</td>'+
            '<td style="padding-left:20px;">'+
                '<div class="form-group">'+
                '<input type="number" name="quantity[]" id="quantity'+count+'" autocomplete="off" class="form-control" min="1" />'+
                '</div>'+
            '</td>'+
            '<td>'+
                '<button class="btn btn-default removeRawRowBtn" type="button" onclick="removeRawRow('+count+')"><i class="glyphicon glyphicon-trash"></i></button>'+
            '</td>'+
        '</tr>';
        if(tableLength > 0) {
            $("#rawTable tbody tr:last").after(tr);
            $("#totalComponents").remove();
            var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+count+'" />';
        } else {
            $("#rawTable tbody").append(tr);
            $("#totalComponents").remove();
            var comp = '<input type="hidden" name="totalComponents" id="totalComponents" value="'+tableLength+'" />';
        }
        $("#rawTable").after(comp);
    }
});}

我在徘徊,是否有办法获得所需的结果。

0 个答案:

没有答案