Creating SELECT Fields PHP

An HTML SELECT tag allows you to list several options that appear as a pull-down menu. I am often in the situation of creating the contents of the list on the fly. Sometimes the contents are pulled from a database, such as for choosing from among users in a Web application. Other times the contents are generated, such as choosing month, day, and year. There are two aspects to this problem. First, there is the fairly simple problem of creating all the values for the OPTION tags. This is best accomplished in a loop. The second issue deals with preselecting one of the options.

Regardless of the source of the contents, database or otherwise, the technique is similar. To illustrate, I'll develop a function for generating three SELECT fields for getting a date from the user: month, day, and year. To generate a list of the months, it is best to draw from an array to display their names. Days and years are numbers, so their values and displayed names are the same.

The options for each selector are generated in a for loop. Months range from 1 to 12, days from 1 to 31. For years, I've chosen to present an 11-year range around the current year. Notice that if you submit a date, it refreshes the page and sets the form with the date you chose. The key is the addition of the if statement. Each time through the loop the current value is tested against the one to be selected.

Date Selector

Date Selector

Date Selector

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics