0

I have the following HTML:

<input type="text" name="inp1" id="inp1" />
<input type="text" name="inp2" id="inp2" />
<input type="text" name="inp3" id="inp3" />

<input type="submit" value="Send" id="clickMe" />

Each time I click on the submit button I should add the values of each inp* to an array so I end up with something like this:

[
     ['inp1' => val1, 'inp2' => val2, 'inp3' => val3],
     ['inp1' => val10, 'inp2' => val20, 'inp3' => val30],
     ['inp1' => val11, 'inp2' => val21, 'inp3' => val31],
     ['inp1' => val12, 'inp2' => val22, 'inp3' => val32]
]

After reading this article I think I could do the following:

var obj = {};
var item = [];

$('#clickMe').click(function() {
    item.push(
        $('#inp1').val(),
        $('#inp2').val(),
        $('#inp3').val()
    ); 
});

But the solution above will end up with a lineal array and not what I want (example here on Fiddle). I have read here and here but I am getting confused.

Also I shouldn't have repeated elements so this:

[
     ['inp1' => val1, 'inp2' => val2, 'inp3' => val3],
     ['inp1' => val1, 'inp2' => val2, 'inp3' => val3]
]

Is invalid. So, how is the right way to deal with this and get a multidimensional array?. Can any give me some help and leave an example so I can get this?

EDIT: As suggested the code should be compatible with most of the browser out there and as for IE should be IE9+

Community
  • 1
  • 1
ReynierPM
  • 17,594
  • 53
  • 193
  • 363
  • Is the question how to create the array, how to avoid duplicates, or how to send it via Ajax? What code do you have? – trincot Nov 11 '16 at 20:02
  • @trincot I was on the middle of an edit, take a look now but in a few words: *how to create a multidimensional array and avoid duplicates* – ReynierPM Nov 11 '16 at 20:04

5 Answers5

1

You could maintain a Set, which is more designed for this purpose than using object properties:

var list = new Set(); // helper object to avoid duplicates
var items = []; // the real 2D array

$('#clickMe').click(function() {
    var item = [
        $('#inp1').val(),
        $('#inp2').val(),
        $('#inp3').val()
    ];
    var key = JSON.stringify(item);
    if (list.has(key)) return; // skip
    list.add(key);
    items.push(item);
    return false; // to avoid that the form submits.
});

If you have many more input elements, it might be worth it to get their values via a loop:

var item = $('form input[type=text]').map(function () { 
    return $(this).val(); 
}).get();

When support for older browsers is needed

... then Sets are not an option. Use a plain object instead:

var list = {}; // helper object to avoid duplicates
var items = []; // the real 2D array

$('#clickMe').click(function() {
    var item = [
        $('#inp1').val(),
        $('#inp2').val(),
        $('#inp3').val()
    ];
    var key = JSON.stringify(item);
    if (list[key] === 1) return; // skip
    list[key] = 1;
    items.push(item);
    return false; // to avoid that the form submits.
});
trincot
  • 317,000
  • 35
  • 244
  • 286
  • I like this one, is clean although I have updated my [Fiddle](https://jsfiddle.net/reynierpm/bz6bp30r/1/) and is not working. I am using Chrome, can you check? – ReynierPM Nov 11 '16 at 20:20
  • Your fiddle does not have any other code to actually do something with the array. – trincot Nov 11 '16 at 20:22
  • I have [updated it](https://jsfiddle.net/reynierpm/bz6bp30r/2/) again, take a look (added `console.log()`). Is there any other way that is compatible with old IE? Maybe 9+? – ReynierPM Nov 11 '16 at 20:24
  • 1
    You want to support IE9? In that case you cannot use Sets. Please put that requirement in your question. I will update my answer then (I don't want to give old-code as answer when it is not specifically asked in the question -- I hope you understand :) ) – trincot Nov 11 '16 at 20:25
  • Understood about forgot to mention compatibility, added to the OP – ReynierPM Nov 11 '16 at 20:28
  • Added IE9 solution to the answer. – trincot Nov 11 '16 at 20:29
0
JSON.stringify(AssocArray);

Create Json string to send over AJAX request.

Or do $("form").serialize() . To know more about this method you can check http://api.jquery.com/serialize/

Rode093
  • 396
  • 2
  • 11
  • What I don't know is how to create the inital `AssocArray` from Javascript – ReynierPM Nov 11 '16 at 19:49
  • Well you could do by running a loop like $("form").children("input").each(function(){ //build up an assoc array }); Another easy method is $("form").serialize(); Check doc and exmaples here http://api.jquery.com/serialize/ – Rode093 Nov 11 '16 at 19:58
  • I have edited the OP, take a look, this is not exactly what I am looking for. After have the array I could use your suggestion though – ReynierPM Nov 11 '16 at 20:02
0

To create the equivalent of an associative array in Javascript, you need an object. The object properties act like array keys would in a language like PHP. For example:

var myObject = {
    a: [1,2,3],
    b: [4,5,6],
    c: {
        cat:"Fluffy",
        dog:"Fido"
    }
};

Here the properties a and b contain arrays, and the property c contains another object.

fredrover
  • 2,997
  • 2
  • 17
  • 24
0

There is no such concept of an associative array in JavaScript. You should be hydrating an object and then sending that as an XMLHttpRequest either by form-encoding or JSON-encoding the object.

$('#clickMe').click(function() {
    var obj = {};
    obj[ $('#inp1').attr('name') ] = $('#inp1').val();
    obj[ $('#inp2').attr('name') ] = $('#inp2').val();
    obj[ $('#inp3').attr('name') ] = $('#inp3').val();
    console.log(obj) // see desired data-structure
    console.log(obj.inp1); // get inp1 val
    console.log(obj['inp1']); // get inp1 val again
});

This example would also be better if you could loop on the input elements with something like:

var elms = $('form input');
var obj = {};
for ( var i = 0; i < elms.length; i++ )
{
    obj[ $(elms[i]).attr('name') ] = $(elms[i]).val();
}
John Foley
  • 4,373
  • 3
  • 21
  • 23
0

You can try to wrap up a JavaScript Object for each key value pair (attributes of the input fields) then push each object into an array. The following example might help:

var item = [];
$('#clickMe').click(function() {
    var val1 = $('#inp1').val();
    var val2 = $('#inp2').val();
    var val3 = $('#inp3').val();
    var obj = {
        inp1: val1,
        inp2: val2,
        inp3: val3
      };
item.push(obj);
});
//your code for AJAX goes here

I hope this helps.

Abrar
  • 6,874
  • 9
  • 28
  • 41