Reputation: 3074
I have an an array as follows:
var data = new Array();
if(j==1){
data['name']=$('input:text[name=full_name]').val();
data['email']=$('input:text[name=email]').val();
data['password']=$('input:password[name=password]').val();
data[' ']=$('input:password[name=retype_password]').val();
}
I want to loop through with this array as follows:
$.each(data,function(index,value){
alert(index + ": " + value );
});
But no alert box is appeared that proves .$each() does not work. How can I fix this issue?
Upvotes: 1
Views: 68
Reputation: 862
try this way
var j =1;
var data = {};
if (j == 1) {
data['name'] = 'Rachit';
data['email'] = '[email protected]';
data['password'] = 'rachit';
data[' '] = 3;
}
$.each(data, function (index) {
alert(index + " : " + data[index] );
});
http://jsfiddle.net/patelrachith/FZy3b/1/
Upvotes: 0
Reputation: 12290
Use object instead of an array
var data = {};
if (j==1) {
data['name']=$('input:text[name=full_name]').val();
data['email']=$('input:text[name=email]').val();
data['password']=$('input:password[name=password]').val();
data[' ']=$('input:password[name=retype_password]').val();
}
$.each(data, function(i, v) {
alert(i, v);
});
An array maps index to a value, not key to a value, i.e.:
var A = [];
A.push('John');
A.push('Mike');
A.push('Sally');
console.log(A[1]); // prints Mike
Upvotes: 1
Reputation: 388436
What you have is an object(key value pair) not an Array where objects are stored using an index.
So you need to create data
as an object, not as an array
var data = {};
Demo: Fiddle
Upvotes: 3