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?
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 ofnew Array()) and pushes a map (created with{}) into it: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:
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).