Daniel Anderson Daniel Anderson - 3 months ago 15
ASP.NET (C#) Question

How to iterate through form fields using jQuery/Javascript

I have a form for an ASP.NET WebForms app that looks like this:

<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:

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 (""). 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?

Answer

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>

Comments