Page 1 of 1
Dynamically changing dropdowns
Posted: Tue Jul 18, 2006 6:00 am
by hame22
Hi
On my website I have employed a category and subcategory system.
A category can have many subcatergories and these are stored in my database
I am trying to set up a form that has a dropdown list of categories to choose from and then a second dropdown list that then displays the chosen categories subcategories.
Is there a way to achieve this in php?
Many thanks in advance
Posted: Tue Jul 18, 2006 6:24 am
by mattcooper
Javascript would probably be your best bet, as this would avoid the necessity of submitting a form to populate the second dropdown. Also, maybe AJAX?
Posted: Tue Jul 18, 2006 6:38 am
by hame22
yes I had thought about Javascript but is this method possible when obtaining the values from a database?
Thanks
Posted: Tue Jul 18, 2006 6:45 am
by Ollie Saunders
You will have to use JavaScript.
You don't necessarily have to use AJAX but it is and less complicated form logic wise, although if you have never used it before its probably not the best choice.
There are a couple of ways I can see you going about this.
Method One
Force the user to make a choice from the first select field and use onchange="this.form.submit()" to submit the form immediately after a change is made. Then use some PHP logic to determine that the submission was caused by the onchange event of the select and not a submit button possibly like this:
Code: Select all
if (!isset($_POST['submitButtonName'])) {
// submission caused by JS
} else if (!empty($_POST)) {
// standard submission
} else {
// no submission
}
In the "submission caused by JS" regenerate the whole page plus the second select with the stuff depending on the first.
Method Two
Note: I wouldn't advice this method for scalability reaons, you have to send to the client ALL the options possible for the second select
Send to the client some JSON (google that if you need) from PHP describing the content of the second select dependent on the value of the first for all value the first can have. Use JS to change the options in the second select after an onchange event on the first.
This will be much faster than method one and probably the easiest to implement as long as you know your JS.
Method Three
Use AJAX. After an onchange event on the first select use JS and an asynchonus request to get JSON (not strictly AJAX but you really don't need XML for this) for the second select specifically based on the selection made in the first.
This method gives you the best results for a system with many possible options because only the exact amount of data required is requested.
Posted: Tue Jul 18, 2006 8:06 am
by Roja
No need for AJAX or JSON. What you want to do is called a Chained Select or Chained Selector. Google for either.
Alternatively, here is a decent link with an example:
http://www.dynamicdrive.com/dynamicinde ... /index.htm