简体   繁体   English

序列化带有相应标签的表单

[英]Serializing a form with corresponding labels

I am using jQuery to serialise a form, and post it's values to a url which stores them as name/value pairs in a DB. 我正在使用jQuery序列化表单,并将其值发布到将其作为名称/值对存储在数据库中的url中。 However, the names and IDs of each form field are dynamically generated (eg f4sgg-342 ), and are hence not describing the specific field. 但是,每个表单字段的名称和ID是动态生成的(例如f4sgg-342 ),因此没有描述特定字段。 I have no control of the system generating these fields. 我无法控制生成这些字段的系统。

There are however corresponding labels, which contain a description of the specific form field - they also contain a for=" f4sgg-342 " attribute, allowing me to link the label to the right field. 但是,有相应的标签,其中包含对特定表单字段的描述-它们还包含for =“ f4sgg-342 ”属性,允许我将标签链接到正确的字段。

I have used the regular form.serialize() function: 我已经使用了常规的form.serialize()函数:

<script type="text/javascript">
$(document).ready(function() {
    var form = $("#some-form");

    $("#some-form").submit(function(e) {
        $.ajax({
            type: "POST",
            url: 'https://example.com/post.php',
            data: form.serialize(),
            success: function(response) {
                console.log(response);
                $("#result").html(response);
            },
            error: function() {
                alert('Error Submitting');
            }
        })
    })
})

But I am quite clueless how to replace the form field names with the labels, when I post pass the content to the url. 但是,当我将内容传递到url时,如何将表单字段名称替换为标签却一无所知。 Considering using .labels() of jQueryUI - but again - can't seem to be able to "connect the dots" 考虑使用jQueryUI的.labels() -但同样地-似乎无法“连接点”

Any suggestions? 有什么建议么? Thank you! 谢谢!

How about this?. 这个怎么样?。 Lets supose that you have a button in the bottom of the form (with id submit) that is attached to a click event: 假设您在表单底部(带有ID提交)的按钮上附加了click事件:

$("#submit").click(function(){

    var originalSerialized = $("#some-form").serialize();
    console.log(originalSerialized);

    var splitedString = originalSerialized.split("&");
    console.log(splitedString);

    var newString = "";

    $.each(splitedString, function(i, element){

        var strangeName = element.substr(0, element.indexOf('='));

        if(newString == "")
            newString = $("label[for='"+strangeName+"']").html() + element.substr(element.indexOf('='));
        else
            newString += "&" + $("label[for='"+strangeName+"']").html() + element.substr(element.indexOf('='));

    })

    console.log(newString);

    //Here, you do the AJAX and the data is the newString variable

})

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

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