Can anyone tell me what I've done wrong?
Very little! :-)
- In your
$.map callback, the first argument will be the element, not its value, so you just use its value property.
- You also were wrapping it in an array (
return [value]), which you don't want to do; $.map will build an array from the values you return from each call to the callback.
- Also, you were using
input.items where you wanted input.item.
You don't need to declare the index argument if you don't use it.
$('button#despatchOrder').on('click', function() {
var values = $("input.item"); // ***
var myArray = $.map(values, function(element) { // ***
return element.value; // ***
});
console.log(myArray);
});
Example:
$('button#despatchOrder').on('click', function() {
var values = $("input.item");
var myArray = $.map(values, function(element) {
return element.value;
});
console.log(myArray);
});
<input name="item[1]" class="item" value="1">
<input name="item[2]" class="item" value="50">
<input name="item[3]" class="item" value="12">
<button id="despatchOrder">Despatch</button><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That gives you the items in the array without using the item[1] and such name. What you've shown that you want
items = [
1 => 1,
2 => 50,
3 => 12
]
isn't valid JavaScript. The above gives you:
myArray = ["1", "50", "12"];
but if you want name/value pairs, probably an array of objects would be best:
myArray = [
{name: "1", value: "1"},
{name: "2", value: "50"},
{name: "3", value: "12"}
]
To do that:
var myArray = $.map(values, function(element) {
return {name: element.name.substring(5, 6), value: element.value};
});
Or of course if you want the whole name item[1], just remove the substring part.
Example:
$('button#despatchOrder').on('click', function() {
var values = $("input.item");
var myArray = $.map(values, function(element) {
return {name: element.name.substring(5, 6), value: element.value};
});
console.log(myArray);
});
<input name="item[1]" class="item" value="1">
<input name="item[2]" class="item" value="50">
<input name="item[3]" class="item" value="12">
<button id="despatchOrder">Despatch</button><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Just for completeness, you can also use the other map function (jQuery has two), but it doesn't do you any real good here:
var myArray = values.map(function() {
return this.value;
}).get();
Note the .get() at the end.