Make PHP select the correct Select option
Posted by admin on September 25, 2008
Sometimes you just want to select the correct option from a drop-down field (aka Select element in an HTML form).

If you have a Preferences or Account Setting page in your web application, or something similar, chances are you sometimes need to display the correct option in an HTML form Select element. For example, if the end-user selected a specific country during the original registration process, you want to make sure that the correct country gets displayed in the Account Settings page, right?
And sometimes, you just have a pre-determined number of options in a select (or drop-down) field. For example, countries, states, regions or products. Not everyone has all of those option values and descriptions (i.e., text) in a database, and so you end up having to select the correct option as soon as the page has loaded.
The solution that I have used in this situation works really well if you get the value (for example, the name of the country) from PHP or ASP and want to plug it into your JavaScript code. We are using getElementById(), so your form elements need to have an ID tag with a value.
Obviously, this also requires a modern web browser that can handle the associated JavaScript. Unless you’re several years behind updating your web browser, however, you should have no problems.
The approach is fairly simple, and the only tricky thing is to remember the proper syntax. Here is an example with PHP and JavaScript:

That’s it.
Filed Under: Applications and Software Tools, JavaScript, Web Design and Development