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
}
.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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With