Skip to content Skip to sidebar Skip to footer

Create Dynamic Drop Down List

I'm searching the internet now for quite some time to find a proper solution but I was not successful so far. What I try to achieve: I create a dynamic drop down box with provinces

Solution 1:

Unfortunately, the approach you outline above will not work. When you use php inside a javascript segment, you have to remember that the php code will be evaluated when the file containing the javascript is requested from the server only. Anything the PHP code has output during the request (e.g. via an 'echo' command) will then become part of your javascript function. In the case above, you have not output anything so your javascript code will essentially read .innerHTML=\" \"; once the page loads. Even if you did output data there, it would not be dynamic.

As I see it, you have 3 options:

  1. Use AJAX to load the HTML for the second drop down from a php file. This is definitely the way to go if you are already familiar with AJAX, but could be a bit tricky otherwise. If you aren't familiar, I would definitely recommend going through a few tutorials before trying to implement this option.

  2. Reload the page when the user changes the first drop down, and use a query string parameter to tell your PHP script what province has been selected. This is probably not a very good option, especially if this pair of drop downs is part of a larger form that the user might have already entered some data into.

  3. Have your PHP output the HTML for the first drop down, and then a separate drop down for each province that lists its respective districts. (So if you have 10 provinces, you would create 11 drop downs total.) Then you would use the CSS style display: none; to hide the secondary drop downs and use javascript to toggle their style to display: inline-block;. This option is not ideal for large numbers of options, because you are loading tons of potentially unnecessary data.

Out of curiosity, why are you storing the province data in the user's $_SESSION variable? I typically try to reserve that for user specific data or information pertaining to the state of the interface.

Post a Comment for "Create Dynamic Drop Down List"