First of all, you should use different names for the text fields, unless you want to use this: name="user[]" which would have an array for item name, item number and stock quantity.
But in this case, better do something like this:
HTML Code:
<form action="nextPage.html" method="post" onsubmit="return getData(this);">
PHP Code:
<script type="text/javascript">
function getData(form) {
var data = new Array();
for (var i = 0; i < form.elements.length; i++) {
var key = form[i].name;
var val = form[i].value;
var element = {};
element[key] = val;
data.push(element);
}
return false;
}
</script>
EXPLANATION:
The onsubmit event handler expects a boolean true or false to eventually submit the form or not. You prevent it from being sent by returning false.
The function:
It is passed this, which refers to the element in which the function call is located: the form element.
data will be the array to store the field names and their values.
You will want to loop through the form elements, via the elements property, and as Javascript lacks associative arrays, that is arrays whose indexes can be strings, which would be perfect to map each pair 'element_name' -> 'element_value', Javascript makes use of object literals, which are elements like this:
PHP Code:
var object = {
'property1' : 'value1',
'property2' : 'value2',
...
'propertyN' : 'valueN'
};
it is like a generic object whose properties are created and populated dynamically.
you will access them this way:
object.property1 // dot notation
or
object['property1'] // square brackets notation
this helps simulating associative arrays.
You can combine this with arrays if you want to keep an array notation:
PHP Code:
var list = [
{'name' : 'name1', 'value' : 'value1'},
{'name' : 'name2', 'value' : 'value2'},
...
{'name' : 'nameN', 'value' : 'value3'}
]; // literal array creation, without the need of the constructor (new Array())
in this case you will access them like this:
list[0].name <--- list[0].value
or
list[0]['name'] <--- list[0]['value']
A last thing to mention is that in this function, this wouldn't work:
var element = {key : val};
the square brackets notation must be used instead, as seen above.
Hope this helps!
Bookmarks