dqeq885710
2016-02-22 10:59
浏览 85

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

We are doing a proof of concept for an application where in the HTML elements are generated from the fields configured by the user.

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;

<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. We have a JavaScript function which takes the input from these elements and and searches for the data depending on the provided search keys. 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. The line var inputValues = formElement.serializeArray(); is always empty. I read that the serialize() and serializeArray() only serializes the elements inside the provided element.

Can you please give me some hints or solution to serialize all the elements with the provided form_id? i will have a div element that encloses the provided HTML output and this div can contain any type of elements; 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.

Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshicuo4844 2016-02-22 11:08
    已采纳

    The line var inputValues = formElement.serializeArray(); is always empty.

    your generated HTML is the problem. If you inspect it carefully you can see that the form tag is empty and all the elements fall out of it.

    Taken from your 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.

    And then coming to your script,

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

    this gives you the form tag, (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.

    点赞 打赏 评论

相关推荐 更多相似问题