Dropdown list with options from database record using jQuery
We can add options to a list box by using records from a database table. Records from table will be returned in JSON string format and jQuery will be used to add options to list box. For this example we will keep three pages.
You download all the files at the end of this page
This is the front end page to display the list box with JQuery code to collect the data.
This is the backend page to connect to database and return records as JSon string
Backend Script student-data.phpWe have used PHP PDO to connect to database table where we kept our student table. You can create your table by using sql_dump of the student table.
We first connect to database by using config.php file.
Then write the query in a variable $sql Execute the query and finally get the array of records stored in $result
Using this array we print the Json string.
Full code is here
student-list.phpThis script creates the dropdown list box and by using getJSON function we will connect to our backend script student-data.php and get the JSON string of data.
Now using each loop we will create one string to add options to our listbox.
In the HTML part we have the student dropdown list. Here is the complete code of student-list.php page.
Reading the selected text of value of a dropdown list boxBy using above code we have displayed a list box, now we will trigger or execute further code to know the option selected by the user.
For this we will use jQuery change function. This function will be fired when any option is changed by user.
In our student dropdown list we have student ID as option and student name as text displayed against each option.
To read the option we have to use val() function
To read the text part we have to use option:selected.Text
Here is the code to collect selected option ( the line to collect text part is commented )
Inside your zip file this code is kept in a separate file student-list2.php file.