I have a function that should
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?
You should define a object, not an array
var data = {};
data[name] = value;
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, ie an Object
instead of an Array
. Try this, instead:
var data = {}; // NB: *not* an array
$('form :input').each(function() {
data[this.name] = this.value;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.