简体   繁体   English

如何使用jQuery / Javascript遍历表单字段

[英]How to iterate through form fields using jQuery/Javascript

I have a form for an ASP.NET WebForms app that looks like this: 我有一个如下所示的ASP.NET WebForms应用程序表单:

<div id="signinForm">
    <div class="form-inline form-group-sm">
        <div class="input-group">
            <label for="MemberName" class="sr-only">Email Address :</label>
            <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
            <input type="email" required id="MemberName" placeholder="Email Address" class="form-control">
        </div>
        <div class="input-group">
            <label for="Password" class="sr-only">Password :</label>
            <input type="password" required id="Password" placeholder="Password" class="form-control">
        </div>
        <button id="signInBtn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button>
    </div>
</div>

I want to build a JSON object from the form fields to pass to a web service, and right now I'm using this: 我想从表单字段构建JSON对象以传递到Web服务,现在我正在使用此对象:

            var formData = {};
            $(signinForm).find(':input').each(function () {
                formData[this.name] = this.value;
            });

            var json = JSON.stringify({ NewMember: formData });

If I inspect the JSON object built, the form fields are not included in the object -- they're blank (""). 如果检查构建的JSON对象,则该对象中不包含表单字段-它们为空(“”)。 What am I missing in the code I have to achieve what I want, which is to include the name/value pairs of the form fields as part of the created JSON object? 我要实现所需的代码中缺少什么,那就是将表单字段的名称/值对作为创建的JSON对象的一部分包括在内?

This works. 这可行。 Please try. 请试试。

 var formData = {}; $('#signinForm').find('input').each(function() { formData[this.id] = this.value; }); var json = JSON.stringify({ NewMember: formData }); console.log(json); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="signinForm"> <div class="form-inline form-group-sm"> <div class="input-group"> <label for="MemberName" class="sr-only">Email Address :</label> <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span> <input type="email" required id="MemberName" placeholder="Email Address" class="form-control"> </div> <div class="input-group"> <label for="Password" class="sr-only">Password :</label> <input type="password" required id="Password" placeholder="Password" class="form-control"> </div> <button id="signInBtn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button> </div> </div> 

I used a small jQuery helper function to do exactly this (I found the answer on another StackOverflow answer but can't actually find the original question to quote it for you) 我使用了一个小的jQuery辅助函数来做到这一点(我在另一个StackOverflow答案中找到了答案,但实际上找不到原始问题来为您引用)

Helper Function 辅助功能

I placed the below code in a separate javascript helper file to make it globally available across my app 我将以下代码放在单独的javascript帮助文件中,以使其在我的应用程序中全局可用

$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

The actual form itself was declared as: 实际的形式本身被声明为:

<form id="frmShippingAccount" class="form-inline shipping-account-form" action="#">
    <input type="text" name="Name" />
</form>

Then, inside the on-click action of my form's Save button... 然后,在表单的“保存”按钮的点击动作中...

var shippingAccountForm = JSON.stringify($("#frmShippingAccount").serializeObject());

The serializeObject function would get each element in my form, and push the Name attribute into a JSON object as the property name, and the corresponding value as the value. serializeObject函数将获取我表单中的每个元素,并将Name属性作为属性名称推送到JSON对象中,并将相应的值作为值。

Eg { "Company":"", "Address1":"", "Address2":"", "City":"", "Zip":"", "Country":"" } 例如{“ Company”:“”,“ Address1”:“”,“ Address2”:“”,“ City”:“”,“ Zip”:“”,“ Country”:“”}

I think the main issue is that your 'form' is declared as a div, secondly I'm not too sure if your JSON.stringify syntax is correct. 我认为主要问题是您的“表单”被声明为div,其次我不太确定您的JSON.stringify语法是否正确。

The method above made a perfectly formed JSON object which I chucked at a web service, and then parsed into a Newstonsoft JObject with 上面的方法制作了一个完美构成的JSON对象,我将其放在Web服务上,然后解析为Newstonsoft JObject

JObject jData = JObject.Parse(jsonString); JObject jData = JObject.Parse(jsonString);

where jsonString was a string of the JSON object passed from my ajax call 其中jsonString是我的ajax调用传递的JSON对象的字符串

Hope that helps! 希望有帮助!

Try to remove the double point 尝试删除双点

$(signinForm).find('input').each(function () {

Also the input items in your html example don't have name attributes although you are using them here html示例中的输入项也没有名称属性,尽管您在此处使用它们

 formData[this.name] = this.value;

The input fields are missing name attribute 输入字段缺少名称属性

 var formData = {}; $(signinForm).find('input[name]').each(function () { formData[this.name] = this.value; }); var json = JSON.stringify({ NewMember: formData }); console.log(json) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="signinForm"> <div class="form-inline form-group-sm"> <div class="input-group"> <label for="MemberName" class="sr-only">Email Address :</label> <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span> <input type="email" name="email" required id="MemberName" placeholder="Email Address" class="form-control"> </div> <div class="input-group"> <label for="Password" class="sr-only">Password :</label> <input type="password" required id="Password" placeholder="Password" class="form-control"> </div> <button id="signInBtn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button> </div> </div> 

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

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