Use name attribute for HTML input to get the object
In ExpressJS using body-parser, there is a function to parse as a JavaScript object (or JSON, I'm not entirely sure) a set of input elements that have the same name attribute with specific keys.
HTML (for example) :
<input type="text" class="name" name="name[foo]" placeholder="input1"/>
<input type="text" class="name" name="name[bar]" placeholder="input2"/>
JavaScript (for example) :
var obj = req.body.name;
The object obj
is understood by JavaScript as{ "foo" : input1, "bar" : input2 }
I am trying to get similar functionality using standard jQuery to handle multiple related input forms. What I have tried so far - to no avail - is the following:
$(".name")
gives an object containing literal HTML (not useful for capturing key-value pairs).
$(".name").map(function () {return $(this).val();}).get();
prints an array of values, but contains no keys.
$("input[name='name']")
and $("input[name='name[]']")
give nothing.
I also tried the following to convert the inputs to an array, but it still doesn't serve the purpose of pulling information out of the form as a JavaScript / JSON object:
$.fn.inputsToArray = function () {
var values= [];
$.each(this, function (i, field) {
values.push(field.value);
});
return values;
};
Is there a way to accomplish what I am trying to do without NodeJS / body-parser?
Decision:
Thanks to gaetanoM's excellent solution (taken below), I was able to create a generic jQuery function that can be called on any jQuery object (obviously this' will only work if the element is in format <input ... name="example[key]" ... />
, but I'm disconnecting).
The function is called like this:
var output = $(":input[name^=example]").inputsToObject();
The function is defined as follows:
$.fn.inputsToObject = function () {
var values = {};
values = $(this).get().reduce(function (acc, ele) {
var key = ele.name.match(/\[(.*)\]$/)[1];
acc[key] = $(ele).val();
return acc;
}, {})
return values;
}
source to share
For the first, you need $ (': input [name ^ = name]') to select all input fields that have a name attribute starting with a name. With help . Get () you convert the jQuery result to an array that you can apply to . reduce () :
var result = $(':input[name^=name]').get().reduce(function(acc, ele) {
var key = ele.name.match(/\[(.*)\]$/)[1]; // get the key
acc[key] = ele.getAttribute('placeholder'); // add to retval
return acc;
}, {});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="name" name="name[foo]" placeholder="input1"/>
<input type="text" class="name" name="name[bar]" placeholder="input2"/>
source to share