0

I have a function that should

  1. collect all input data in an array
  2. put that array in JSON format (to be used as ajax post data)

Here's what I have, which seems like it should work, but when I log the stringified version, all I get is [].

function get_data_from_form() {
 var data = [];
 var inputs = $('form').find('input');
 $.each(inputs, function (index, value) {
 var name = $(this).attr('name');
 data[name] = value; // How should this change?
 });
 console.log('stringified data: ' + JSON.stringify(data)); // -> []
}

The desired output should be something like: "{ fname: 'turd', lname: 'ferguson' }"

What am I doing wrong? Would it be easier to just make a string and concat the name/value pairs?

asked Aug 13, 2014 at 12:54
7
  • how do you correlate the fields? Commented Aug 13, 2014 at 12:55
  • 4
    What am I doing wrong? You are confusing arrays and objects. Your desired output is not an array, it's an object. Commented Aug 13, 2014 at 12:55
  • @MattBurland Thanks, I was confusing objects and arrays. Commented Aug 13, 2014 at 13:11
  • @TravisHeeter that's actually a trivial problem compared to the issue of extracting the value... :( Commented Aug 13, 2014 at 13:11
  • @Alnitak You mean that I'm using the wrong selector: $('form').find(' input')? I actually just used that to simplify things I'm actually using classes, and it seems to work fine. Commented Aug 13, 2014 at 13:13

2 Answers 2

3

You should define a object, not an array

var data = {};
data[name] = value;
answered Aug 13, 2014 at 12:55
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This and @Alnitak's 'this.value' worked. When I used data[name] = value; it gave me a bunch of metadata. data[name] = this.value worked.
Oh, it gave me a bunch of metadata for the textarea, targeted with a class, and not input, so maybe that's why I got the metadata.
2

Your value extraction field is wrong - in the .each call the value parameter is the current element, not its value. Also, you need to capture the fields in a key/value store, i.e. an Object instead of an Array. Try this, instead:

var data = {}; // NB: *not* an array
$('form :input').each(function() {
 data[this.name] = this.value;
});

See http://jsfiddle.net/alnitak/hsy2xd5L/

answered Aug 13, 2014 at 12:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.