我基本上是在尝试根据上一个下拉列表中收集的输入从后端mysql数据库中选择数据。然而,我无法做到这一点。看起来我错过了什么,但无法弄清楚!!
这是我正在尝试的代码片段。。
376 <div class="col-md-4"><label for="doctor">Doctors:</label></div>
377 <div class="col-md-8">
378 <select name="doctor" class="form-control" id="doctor" required="required">
379 <option value="" disabled selected>Select Doctor</option>
380
381 <?php display_medis(); ?>
382 </select>
383 </div><br/><br/>
384
385
386 <script>
387 document.getElementById('doctor').onchange = function updateFees(e) {
388 var selection = document.querySelector(`[value=${this.value}]`).getAttribute('data-value');
389 document.getElementById('docFees').value = selection;
390 };
391 </script>
392
393
394 <div class="col-md-4"><label for="consultancyfees">
395 Consultancy Fees
396 </label></div>
397 <div class="col-md-8">
398 <!-- <div id="docFees">Select a doctor</div> -->
399 <input class="form-control" type="text" name="docFees" id="docFees" readonly="readonly"/>
400 </div><br><br>
功能代码
function display_medis()
{
global $con;
$query = "select med_name,med_id,mrp from med_inv";
$result = mysqli_query($con,$query);
while( $row = mysqli_fetch_array($result) )
{
$med_name = $row['med_name'];
$mrp = $row['mrp'];
$med_id=$row['med_id'];
echo '<option value="' .$med_name. '" data-value="'.$mrp.'" >'.$med_name.'</option>';
//echo '<option value="' .$med_name. '" data-value="'.$mrp.'" data-spec="'.$med_id.'">'.$med_name.'</option>';
//echo '<option value="' .$med_name. '" >'.$med_name.'</option>';
//echo '<option value="' .$mrp. '" >'.$mrp.'</option>';
}
}
任何建议。
[屏幕截图]在此处输入图像描述
在处理select下拉选择值的原始JS脚本中存在一些语法问题。
请更改
<script>
document.getElementById('doctor').onchange = function updateFees(e) {
var selection = document.querySelector(`[value=${this.value}]`).getAttribute('data-value');
document.getElementById('docFees').value = selection;
};
</script>
至
<script>
document.getElementById('doctor').onchange = function updateFees(e) {
var selection=this.selectedOptions[0].getAttribute('data-value');
document.getElementById('docFees').value = selection;
};
</script>
沙盒链接(工作(:
http://www.createchhk.com/SOanswers/SOtest5Oct2022.html
function display_medis(){
global $con;
$query = "select med_name,med_id,mrp from med_inv";
$result = mysqli_query($con,$query);
$option = '';
while( $row = mysqli_fetch_array($result) )
{
$med_name = $row['med_name'];
$mrp = $row['mrp'];
$med_id=$row['med_id'];
$option .= '<option value="' .$med_name. '" data-value="'.$mrp.'" >'.$med_name.'</option>';
}
echo $option;
}
现在你的脚本代码应该看起来像这个
<script>
$('#doctor').on('change',function(e){
var selection = $('#doctor option:selected').val();
$('#docFees').val(selection);
});
</script>