简体   繁体   English

使用jQuery序列化表格外的动态生成的HTML输入元素

[英]serialize the dynamically generated HTML input elements outside the form using jQuery

We are doing a proof of concept for an application where in the HTML elements are generated from the fields configured by the user. 我们正在为应用程序进行概念验证,其中HTML元素是由用户配置的字段生成的。

The sample configuration is as follows; 示例配置如下:

/// Customer SAM
$response = array(
    array (
        NAME => CUSTOMER,
        TYPE => SAM,
        ENABLEDBUTTONS => SEARCHANDADD,
        TABLENAME => "OCRD",
        FIELDS => array (
            array(
                NAME => "lblCustNr",
                TYPE => LABEL,
                WIDTH => "100px",
                VALUE => "Customer Nr.:"
            ),
            array(
                NAME => "customernr",
                TYPE => TEXT,
                WIDTH => "100px",
                COLUMNNAME => "cardcode",
                VALUE => ""
            ),
            array(
                NAME => "lblCustName",
                TYPE => LABEL,
                WIDTH => "100px",
                VALUE => "Customer Name:"
            ),
            array(
                NAME => "customername",
                TYPE => TEXTAREA,
                COLUMNNAME => "cardname",
                ROWS => "5",
                COLUMNS => "50",
                VALUE => ""
            ),
            array (
                NAME => ADDRESS,
                TYPE => SAM,
                ENABLEDBUTTONS => SEARCH,
                TABLENAME => "CRD1",
                FIELDS => array(
                    array(
                        NAME => "lblStreet",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Street:"
                    ),
                    array(
                        NAME => "street",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "Street",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblStreetNo",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Street No:"
                    ),
                    array(
                        NAME => "streetNo",
                        TYPE => TEXT,
                        WIDTH => "30px",
                        COLUMNNAME => "StreetNo",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblCity",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "City:"
                    ),
                    array(
                        NAME => "city",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "City",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblZipcode",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "ZipCode:"
                    ),
                    array(
                        NAME => "zipcode",
                        TYPE => TEXT,
                        WIDTH => "50px",
                        COLUMNNAME => "ZipCode",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblState",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "State:"
                    ),
                    array(
                        NAME => "state",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "State",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblCountry",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Country:"
                    ),
                    array(
                        NAME => "country",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "Country",
                        VALUE => ""
                    )
                )
            )
        ),
        SEARCHQUERY => "
            SELECT cardcode, cardname
            FROM [{DATABASENAME}].dbo.OCRD
            [{WHERECLAUSE}]
        "
    )
);

By using a recursive method, the HTML elements are generated as follows; 通过使用递归方法,HTML元素的生成如下:

<form method="POST" id="CustomerSAM"></form>
<p>Customer Nr.:</p>
<input name="customernr" id="customernr" form_id="CustomerSAM" type="text" style="width:100px" value=""
/>
<p>Customer Name:</p>
<textarea name="customername" form_id="CustomerSAM" rows="5" cols="50"></textarea>
<form method="POST" id="AddressSAM"></form>
<p>Street:</p>
<input name="street" id="street" form_id="AddressSAM" type="text" style="width:100px" value="" />
<p>Street No:</p>
<input name="streetNo" id="streetNo" form_id="AddressSAM" type="text" style="width:30px" value="" />
<p>City:</p>
<input name="city" id="city" form_id="AddressSAM" type="text" style="width:100px" value="" />
<p>ZipCode:</p>
<input name="zipcode" id="zipcode" form_id="AddressSAM" type="text" style="width:50px" value="" />
<p>State:</p>
<input name="state" id="state" form_id="AddressSAM" type="text" style="width:100px" value="" />
<p>Country:</p>
<input name="country" id="country" form_id="AddressSAM" type="text" style="width:100px" value="" />
<br />
<br />
<p>
    <input name="btnSearch" form_id="AddressSAM" class="button" type="submit" value="Search" tag="AddressSAM" onClick="return searchInSAM($(this));"
    /> |
    <input type="button" form_id="AddressSAM" class="button" value="Clear" onClick="return clearForm($(this));" />
</p>
<br />
<br />
<p>
    <input name="btnSearch" form_id="CustomerSAM" class="button" type="submit" value="Search" tag="CustomerSAM" onClick="return searchInSAM($(this));"
    /> |
    <input name="btnAdd" form_id="CustomerSAM" class="button" type="submit" value="Add" tag="CustomerSAM" /> |
    <input type="button" form_id="CustomerSAM" class="button" value="Clear" onClick="return clearForm($(this));" />
</p>

This approach is followed as the dynamic form generation for sub-modules were resulting in inappropriate form generation (nested forms with no form tag). 遵循此方法,因为子模块的动态表单生成导致不适当的表单生成(没有表单标签的嵌套表单)。 HTML5 standard is used and the form_id attribute for each input and submit element is set. 使用HTML5标准,并为每个输入和提交元素设置form_id属性。 We have a JavaScript function which takes the input from these elements and and searches for the data depending on the provided search keys. 我们有一个JavaScript函数,该函数从这些元素中获取输入,并根据提供的搜索键搜索数据。 The method is as follows; 方法如下。

// search the values depending on the provided input.
            // find the form element from the accessing element.
            function searchInSAM(elem)
            {
                var tagAttr = $(elem).attr('tag');

                // will only hold the id of the form. So will have to preceed with # to access the element.
                var formElementId = $(elem).attr('form_id');
                var formElement = $('#'+formElementId);

                var divElement = formElement;
                while(true)
                {
                    divElement = getParent(divElement);
                    if(divElement.is('div'))
                    {
                        break;
                    }
                }

                var inputValues = formElement.serializeArray();
                var serverAddr = "<?php echo CLIENTHANDLER; ?>";
                var requestParams = {
                    "<?php echo METHODNAME; ?>": "<?php echo SEARCH_METHOD; ?>",
                    "<?php echo SAMNAME; ?>": tagAttr,
                    "<?php echo INPUTVALUES; ?>": JSON.stringify(inputValues),
                    "<?php echo DATABASESERVER; ?>": "SWEPROEBS4",
                    "<?php echo DATABASENAME; ?>": "SBOswedex",
                    "<?php echo USERID; ?>": 1
                };
                console.log(inputValues);
                // transfer the request to the server
                request = ajaxRequest(serverAddr, 
                    "<?php echo POSTMETHOD; ?>", 
                    "<?php echo MULTIPARTFORMTYPE; ?>", 
                    "<?php echo JSONTYPE; ?>", 
                    requestParams);

                // Callback handler that will be called on success
                request.done(function (response, textStatus, jqXHR){
                    //console.log(response);
                    $(divElement).html(response);
                });

                // Callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    // Log the error to the element that is expecting the response
                    $(divElement).html(
                        "The following error occurred: "+
                        textStatus + "<br />" + errorThrown
                    );
                });

                return false;
            }

The search is always empty as the inputValues array is always empty. 搜索始终为空,因为inputValues数组始终为空。 The line var inputValues = formElement.serializeArray(); 这行var inputValues = formElement.serializeArray(); is always empty. 永远是空的。 I read that the serialize() and serializeArray() only serializes the elements inside the provided element. 我读到serialize()和serializeArray()仅对提供的​​元素中的元素进行序列化。

Can you please give me some hints or solution to serialize all the elements with the provided form_id? 您能否给我一些提示或解决方案,以使用提供的form_id序列化所有元素? i will have a div element that encloses the provided HTML output and this div can contain any type of elements; 我将有一个div元素,其中包含提供的HTML输出,并且该div可以包含任何类型的元素; input, select-option, text area, radio buttons, check boxes etc. 输入,选择选项,文本区域,单选按钮,复选框等。

It would be of great help if you can provide me a generic suggestion / solution which caters to all possible elements associated with the form_id. 如果您可以为我提供一个通用的建议/解决方案,以解决与form_id相关的所有可能的元素,那将有很大的帮助。

Thanks in advance. 提前致谢。

The line var inputValues = formElement.serializeArray(); 这行var inputValues = formElement.serializeArray(); is always empty. 永远是空的。

your generated HTML is the problem. 您生成的HTML就是问题所在。 If you inspect it carefully you can see that the form tag is empty and all the elements fall out of it. 如果仔细检查,您会发现form标记为空,并且所有元素都掉了。

Taken from your HTML 取自您的HTML

<form method="POST" id="CustomerSAM"></form>

... ...

<form method="POST" id="AddressSAM"></form>

But you said you maintain the form_id on all the elements that belong to one form, which is fine. 但是您说过要对属于一种表单的所有元素都维护form_id,这很好。

And then coming to your script, 然后进入您的脚本,

var formElement = $('#'+formElementId);

this gives you the form tag, ( Remember that the form tag is empty ). 这为您提供了表单标签,( Remember that the form tag is empty )。 And then you try to do this . 然后尝试这样做。

var inputValues = formElement.serializeArray();

Which will obviously be empty. 显然是空的。

Solution: You can collect all the input elements and append it to a new form and then serialize it. 解决方案:您可以收集所有输入元素并将其附加到新表单中,然后进行序列化。 like below 像下面

 var newForm = $('<form></form>')
 $.each($('[form_id="CustomerSAM"]'),function(i,v){
      $(newForm).append($(this));
 });
 var serializedData = $(newForm ).serializeArray();

Let me know if this helps. 让我知道是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM