I'm using JQuery map function to get an array of inputs' values:
var inputs = $("[id^='field']");
var values = inputs.map(function () {
return $(this).val();
}).get();
I would like to get an associative array of [id, value]:
{
id1: value1,
id2: value2
}
I'm using JQuery map function to get an array of inputs' values:
var inputs = $("[id^='field']");
var values = inputs.map(function () {
return $(this).val();
}).get();
I would like to get an associative array of [id, value]:
{
id1: value1,
id2: value2
}
Share
Improve this question
edited Dec 3, 2011 at 21:31
user166390
asked Dec 3, 2011 at 21:18
HomamHomam
23.9k37 gold badges118 silver badges189 bronze badges
2 Answers
Reset to default 6.map()
returns an array, so if you want an object with id values as the keys, then you can do it like this:
function getFieldValues() {
var values = {};
$("[id^='field']").each(function() {
values[this.id] = this.value;
});
return values;
}
var values = inputs.map(function () {
var obj = {};
obj[ this.id ] = $(this).val();
return obj;
}).get();
If they're not select
or radio
inputs, use this.value
instead of $(this).val()
.
Or if you just wanted an object, use .each
.
var obj = {};
inputs.each(function () {
obj[ this.id ] = $(this).val();
});
If you did want an array of objects, and if your inputs have their name
property, you could also use serializeArray
.
var values = inputs.serializeArray();