Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery variable scope within each

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,

like image 907
Pez Cuckow Avatar asked May 17 '11 00:05

Pez Cuckow


1 Answers

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.

like image 64
alex Avatar answered Oct 01 '22 04:10

alex