• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 528
  • Last Modified:

adding values to javascript array.

I have the following code, looping through form inputs.

Any input whose name has 'bsktMissing' should be added to the array.

I'm specifically calling 'inputs' as an array, instead of object.

		var inputs = [];

			// console.log('key: ' + $(this).attr('name') + '   | Val: ' + $(v).val());
			if( $(this).attr('name').indexOf('Missing') > 1 ){
				inputs[$(this).attr('name').replace('bsktMissing','')] = $(v).val();

Open in new window

If I look at console.log($(this).attr('name').replace('bsktMissing','')) in the loop, the console shows the remaining name string.

If I look at console.log($(v).val()) in the loop, the console shows the input field values.

If I put inputs[ $(this).attr('name').replace('bsktMissing','') ] = $(v).val() in the loop, the inputs array never fills with values.

What am I over looking ?

1 Solution
In Javascript, arrays can only be enumerated.  You can't use them that way.

You could, however, use an object.
var inputs = {};

		// console.log('key: ' + $(this).attr('name') + '   | Val: ' + $(v).val());
		if( $(this).attr('name').indexOf('Missing') > 1 ){
                        var index = $(this).attr('name').replace('bsktMissing','');
			inputs[index] = $(v).val();

Open in new window

It can be a bit confusing, because you assign the value to the key seemingly the way you would in PHP or other languages.  But it's still an object.

To further confuse you, you can access the key/value pair in one of two ways: either inputs.foo or inputs['foo'].  

There's some good information here:
ImaginxAuthor Commented:
You know ... I made sure to make sure everything was in array format - never thought to just switch it to an object to get the associative feature.

That worked perfect though, thanks Zppafan2k2.

Should I be looking out for anything quirky when I pass the jquery object to a php action page, using the $.ajax({}) method ?

Thanks again.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now