PDA

Click to See Complete Forum and Search --> : How to populate and use an array in Javascript?


softwareguy74
Aug 9th, 2004, 11:30 AM
I need to create an array in Javascript in my web page that contains 3 columns:

CategoryID
ReasonID
Value

So for example, I need an array to have the following info:

1,1,Value1
1,2,Value2
1,3,Value3
2,1,Value1
2,2,Value2
2,3,Value3

I will then have 2 comboboxes on my web page. The first combobox will simply contain a CategoryID value. The second combobox needs to be populated based on which CategoryID is selected in combobox 1. So for example, if CategoryID 2 is selected in combobox 1, I need combobox 2 to populated with all values from the array that contain a 2 as the first element.

An example of how to do this would be greatly appreciated.

riis
Aug 9th, 2004, 11:58 AM
I'd use objects for this


// First declare the object type, can be done with a function
function ObjectName(categoryID, reasonID, value)
{
this.categoryID = categoryID;
this.reasonID = reasonID;
this.value = value;
}

// Then declare the array
var myArray = new Array();

// Make an event handler which fills the combo boxes, place it in the body tag, like: <body onload="init()">
function init()
{
// Fill the array
myArray.push(
new ObjectName(1, 1, "Value1"),
new ObjectName(1, 2, "Value2"),
...
new ObjectName(2, 3, "Value3"));

// Loop through the array and fill the combobox
var myCombo = document.getElementById("comboId")';
for(var i = 0; i < myArray.length; i++)
{
myCombo.add(new Option(myArray[i].categoryID, myArray[i].categoryID, false, false);
}

return;

}


I hope you can do the rest from here, like filling the second combo box when the user selects a value from the first. If not just put your questions here.
You might read a bit about event handling in JavaScript. You can put an event on a select box the same way as I did on the body tag. Use the onclick event for this purpose.

softwareguy74
Aug 9th, 2004, 04:55 PM
Seems to be erroring out on the following line:

myCombo.add(new Option(myArray[i].categoryID, myArray[i].categoryID, false, false);

Any ideas?

softwareguy74
Aug 9th, 2004, 05:18 PM
Nevermind, I see that a parenthesis was missing at the end...

riis
Aug 10th, 2004, 02:30 AM
Originally posted by dbassettt74
Nevermind, I see that a parenthesis was missing at the end...
Yup, my mistake, didn't test it