I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?
var data = new Array();
$("#page2 input").each(function(index) {
alert($(this).attr('id'));
data[$(this).attr('id')] = $(this).val();
});
Many thanks for your time,
One thing to know is that an Array
in JavaScript can only ever have positive integer indexes (which are really treated as strings).
When you assign a string to the key, you are assigning properties to an Object
.
You probably want something like this...
var data = {};
$("#page2 input").each(function() {
data[this.id] = this.value;
});
jsFiddle.
If you wanted just the id
attributes.
var data = $("#page2 input").map(function() {
return this.id;
}).get();
jsFiddle.
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