我正在尝试根据下拉选择(instid 和 instfirstname)自动填充一些文本字段(rate1 和rate2)。这些值全部位于一个名为 tbl_insts 的 mysql 表中。我正在尝试 How to Get Content in text field dynamically, based on dropdown selection in php 中找到的解决方案,但无法让它工作。有没有人有什么建议?提前致谢。
这是我的 mysql 表,名为 tbl_insts
instid instfirstname 速率1 速率2
1 约翰 50 45
2 埃里克 25 45
<小时/>这是我的 html 表单。我能够正确填充下拉列表,但不能正确填充文本字段。
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
<小时/>
这是我在标签之前的代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
<小时/>
这是我在 getrates.php 中的代码,与上面的 html 文件位于同一目录中。
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
最佳答案
- 尝试将 data:{inst:inst} 更改为 data:{'inst':inst}
现在您从 getrates.php 返回一个字符串。从您的代码结构来看,您可以这样做:
if (mysql_num_rows($rec) > 0) { while ($res = mysql_fetch_array($rec)) { echo $res['rate1']."|".$res['rate2']; } }
..和
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
希望这有帮助。
关于php - 根据下拉选择自动填充文本字段,其中所有值都来自 MYSQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736911/