I’m trying to create a multidimensinal array that holds an input name and input value of all matched elements.
I’ve tried so many different combinations of code (none worked), so here’s what I currently have:
var numeric = [[],[]];
var counter = 0;
// loop over all inputs
$('.sac').each(function(){
numeric[counter][0] = $(this).attr('name');
numeric[counter][1] = $(this).val();
counter++;
});
Everything I try give me this error: Uncaught TypeError: Cannot set property ‘0’ of undefined
Can you show me what I’m doing wrong? Thanks.
I suppose what I’m really after is:
var a = [];
a['input_name_0'] = 'input_value_0';
a['input_name_1'] = 'input_value_1';
a['input_name_2'] = 'input_value_2';
a['input_name_3'] = 'input_value_3';
a['input_name_4'] = 'input_value_4';
Hi,
You can do it like this:
var numeric = [];
$('.sac').each(function(){
numeric.push([this.name, this.value]);
});
console.table(numeric);
Demo
However, you might want to consider whether an array is the right data structure in this instance.
Maybe an object is better:
var numeric = {};
$('.sac').each(function(){
numeric[this.name] = this.value;
});
console.log(numeric);
{
input_1: "1"
input_2: "2"
input_3: "3"
input_4: "4"
input_5: "5"
input_6: "6"
input_7: "7"
input_8: "8"
input_9: "9"
}
Demo
Using this method, you can easily reference an element by name and get its value:
console.log(numeric.input_1);
=> 1
HTH
Yes this helps! thanks.
Wow, I think I tried every other possible syntax variation ( although incorrect syntax ) expect yours: numeric.push([this.name, this.value]);
I will be passing this data structrue to PHP. Is an object better to pass?
If you are passing it to the PHP script via AJAX, then jQuery’s $.ajax() method expects an object (for the data attribute), so that is the way to go.