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.
student-data.php :
This is the backend page to connect to database and return records as JSon string
JQuery Listbox adding Options from Database Table
Backend Script student-data.php
We 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
<?Php
require "config.php"; // Database Connection
$sql="select id, name from student ";
$row=$dbo->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('data'=>$result));
?>
student-list.php
This 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.
Reading the selected text of value of a dropdown list box
By 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 )
$('#student').change(function(){
//var st=$('#student option:selected').text();
var st=$('#student').val();
alert(st);
});