我创建了一个从数据库中检索的动态选择框。在selectbox中显示成功。但是,它无法将数据显示到文本输入。请帮忙
<form class="col s12" action="" method="post">
<div class="row">
<div class="input-field col s12">
<?php
$npm = $connect->execute("SELECT * FROM tbl_respondent WHERE npm ORDER BY npm ASC");
$row_count = $npm->num_rows;
?>
<select name="npm" class="npm">
<option value="" disabled="disabled" selected>Pilih NPM Anda</option>
<?php
if ($row_count > 0) {
while ($row = $npm->fetch_assoc()){
echo '<option value="'.$row['npm'].'">'.$row['npm'].'</option>';
}
}
else {
echo '<option value="">NPM tidak tersedia</option>';
}
?>
</select>
<label>Pilih NPM</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="alumni_name" name="name" type="text" class="validate">
<label for="alumni_name">Nama Mahasiswa</label>
</div>
</div></form>
javascript代码在这里:
$('select').material_select();
$('.npm').on('change', function(){
var npm = $(this).val();
if (npm) {
$.ajax({
type: 'GET',
dataType: "JSON",
url: 'index/npm_search.php',
data: 'npm=' + npm,
success: function(html){
var toAppend = '';
$.each(html, function(value){
toAppend += '<input id="alumni_name" name="name" type="text" value="'+value.text+'">';
});
$('#alumni_name').append(toAppend);
}
});
}
});
$('select').on('contentChanged', function() {
// re-initialize (update)
$(this).material_select();
});
和npm_search.php在这里:
require_once 'apps/model/class.connection.php';
$connect = new Connection();
if (isset($_GET['npm']) && !empty($_GET['npm']))
{
$name = $connect->execute("SELECT * FROM tbl_respondent WHERE npm = ".$_GET['npm']."ORDER BY name ASC");
$row_count = $name->num_rows;
$return = [];
$i = 0;
if ($row_count > 0)
{
$return[$i] = [
'id' => '',
'text' => 'Pilih NPM anda',
];
while ($row = $name->fetch_assoc())
{
$i++;
$return[$i] = [
'text' => $row['name'],
];
}
}
else {
$return[$i] = [
'id' => '',
'text' => 'NPM Tidak tersedia',
];
}
echo json_encode($return);
}