I have a function that should
- collect all input data in an array
- 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?
2 Answers 2
You should define a object, not an array
var data = {};
data[name] = value;
2 Comments
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;
});
What am I doing wrong?You are confusing arrays and objects. Your desired output is not an array, it's an object.