Dynamically Add Dropdown Values
-
I currently have a child page with a custom form. The form has two dropdown fields. The values on the second dropdown have to be dynamically populated based on the selection of the first dropdown.
After much research and trials, I have come up with a solution that is ALMOST there, but not quite complete.
Currently I have this javascript in my header…
<script> function removeAllOptions(selectbox) { var i; for(i=selectbox.options.length-1;i>=0;i--) { selectbox.remove(i); } } function addOption(selectbox, value, text ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } function SelectCategory(){ removeAllOptions(document.drop_list.category); addOption(document.drop_list.category, "", "Category...", ""); if(document.drop_list.Category.value == 'Fruits'){ addOption(document.drop_list.category,"Mango", "Mango"); addOption(document.drop_list.category,"Banana", "Banana"); addOption(document.drop_list.category,"Orange", "Orange"); } if(document.drop_list.Category.value == 'Games'){ addOption(document.drop_list.category,"Cricket", "Cricket"); addOption(document.drop_list.category,"Football", "Football"); addOption(document.drop_list.category,"Polo", "Polo", ""); } if(document.drop_list.Category.value == 'Scripts'){ addOption(document.drop_list.category,"PHP", "PHP"); addOption(document.drop_list.category,"ASP", "ASP"); addOption(document.drop_list.category,"Perl", "Perl"); } } </script>
In the content of my child page I have this code to generate the first dropdown:
<select name="race" onChange="SelectCategory();"> <option value="Fruits">Fruits</option>"; <option value="Games">Games</option>"; <option value="Scripts">Scripts</option>"; </select>
The ‘option’ lines above are actually being generated from a MySQL query call. But that is not important here.
This is the code for my second dropdown:
<select id="category" name="category"> <option value="">Category...</option> </select>
Right now the code actually works as is. The second dropdown is populated with the values in the SelectCategory function based on the value selected on the first dropdown.
The problem is that right now the values in the function SelectCategory are hardcoded (as you can see). I really need the addOption line values in that function to be generated from a MySQL query that is based on the value selected in the first dropdown.
So if a user selects ‘Games’, I need to run a query that selects all games. That list would then be passed to the function in order to add the list of games to the second dropdown.
I am having a hard time figuring out how to make that happen.
Please help!
Manny
- The topic ‘Dynamically Add Dropdown Values’ is closed to new replies.