Reputation: 21218
This is probably very easy, but I just can't figure out how to solve it right now. Each time a submit button is clicked, the function below checks input field 1 (name), and if not empty adds the value to an associative array, and continue with the description.
What I want is to add a new level 1 element to the array every click, that should hold these value, so that it after three clicks looks like this:
Click 1:
listObject[0]['listObjectName'] = 'Name 1';
listObject[0]['listObjectDesc'] = 'Desc 1';
Click 2:
listObject[1]['listObjectName'] = 'Name 2';
listObject[1]['listObjectDesc'] = 'Desc 2';
Click 3:
listObject[2]['listObjectName'] = 'Name 3';
listObject[2]['listObjectDesc'] = 'Desc 3';
The function:
$('#addListObjectSubmit').click(function (e) {
var listObjectName = $('#m_newListObject').val();
if((listObjectName == null) || (listObjectName == '')) {
return false;
}
else {
listObjects['listObjectName'] = listObjectName;
var listObjectDesc = $('#m_newListObjectDesc').val();
if ((listObjectDesc == null) || (listObjectDesc == '')) {
listObjects['listObjectDesc'] = null;
}
else {
listObjects['listObjectDesc'] = listObjectDesc;
}
}
e.preventdefault();
});
So, what is the best way of dealing with this?
Upvotes: 3
Views: 2526
Reputation: 78691
It will help you a bit if you forget about associative arrays. They only theoretically exist in Javascript. In fact, everything is an object, even arrays. But thinking in data storage terms, you can use a simple array that can only be indexed numerically, or you can use an object as a data map.
The following example creates an array (note the more compact []
instead of new Array()
) and pushes a map (created with {}
) into it:
var listObjects = [];
...
var newElem = {
'listObjectName' : 'Name 1',
'listObjectDesc' : 'Desc 1'
};
listObjects.push(newElem);
Afterwards, you can access this element with listObjects[0]
, if it was the first element in the array.
If you want to access its properties, you can use one of these:
listObjects[0].listObjectName
listObjects[0]['listObjectName']
So you can see that when dealing with objects, you can use the .
notation as well as the bracket notation - they are equivalent, but the latter form makes it look like it is an "associative array" (even more for people coming from PHP).
Upvotes: 5
Reputation: 6777
..you mean, you want to add an "associative array" (they're called "objects", in JavaScript, btw) to an array on each click?
The method to add things to arrays is push()
:
listObject.push({
'listObjectName': 'Name X',
'listObjectDesc': 'Description X'
})
Upvotes: 2