Populate a dropdown list from JSON returned by PHP/MySQL, read the selected value/text, and use the same pattern as the foundation for linked category/state/city lists.
$.getJSON(
"student-data.php"
)
.done(function ( rows ) {
const $select =
$( "#student" ).empty();
$( "<option>", {
value: "",
text: "Select a student"
}).appendTo( $select );
$.each(
rows,
function ( index, row ) {
$( "<option>", {
value: row.id,
text: row.name
}).appendTo( $select );
}
);
});
const value =
$( "#student" ).val();
const text =
$( "#student option:selected" )
.text();
$stmt = $dbo->query(
'SELECT id, name
FROM student
ORDER BY name'
);
echo json_encode(
$stmt->fetchAll(
PDO::FETCH_ASSOC
)
);
See PDO connection and JSON formatting.
Download dropdown-list project Download listbox examples
<?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));
?>$.getJSON("student-data.php", function(return_data){$.each(return_data.data, function(key,value){
$("#student").append(
"<option value=" + value.id +">"+value.name+"</option>"
);
});<html>
<head>
<title>plus2net demo scripts using JQuery</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/
\jquery/1.8.1/jquery.min.js"></script>
<body>
<script>
$(document).ready(function() {
//////////////////////
$.getJSON("student-data.php", function(return_data){
$.each(return_data.data, function(key,value){
$("#student").append(
"<option value=" + value.id +">"+value.name+"</option>"
);
});
});
//////////////////////
});
</script>
<select name=student id=student>
</select>
</body>
</html>$('#student').change(function(){
//var st=$('#student option:selected').text();
var st=$('#student').val();
alert(st);
});
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.