根据所选的下拉列表项动态填充MySQL的多个输入字段 [英] Dynamically fill multiple input fields from MySQL depending on the drop list item selected
问题描述
我已经在网站上搜索了此内容,但空手而归.这是我正在尝试做的事情:
I've searched through the site for this but am coming up empty handed. Here is what I am trying to do:
- 用户从下拉列表中选择一系列选项之一
- 两个输入字段发生变化以反映此选择,用从我的数据库中提取的数据填充输入框
有关我的意思的直观表示,请参见下图:
我知道我需要此解决方案的JavaScript,但是我的JS技能并不那么热(我想我今天的脑力会暂时消失)!
I know that I am going to need JavaScript for this solution, but my JS skills are not so hot (and I think I am having a momentary lapse of brain power today)!
这是我到目前为止的代码(不用担心过时的PHP):
Here's the code that I have so far (don't worry about the outdated PHP):
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_category = $row['item_category'];
$item_title = $row['item_title'];
$item_price = $row['item_price'];
$item_description = $row['item_description'];
echo "<option value=\"".$item_id."\">".$item_title."</option>";
}
?>
</select>
<script>
function update_txt() {
price = document.getElementById('item').selectedIndex.value;
document.getElementById('item_details').value = price;
document.getElementById('item_price').value = price;
}
</script>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
任何帮助将不胜感激!让我知道您是否需要任何澄清. :)
Any help is greatly appreciated! Let me know if you need any clarification. :)
推荐答案
我将对行进行json编码并将其存储为选项上的数据属性,然后在selects change事件上读取属性:
I would json encode the row and store it as a data-attribute on the option, then read the attribute on the selects change event:
<select name="item" id="item">
<?php
while($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
$item_title = $row['item_title'];
echo "<option value=\"".$item_id."\" data-json='" . json_encode($row) . "'>".$item_title."</option>";
}
?>
</select>
<input id="item_details" type="text" class="validate">
<input id="item_price" type="text" class="validate" value="$">
<script>
$('#item').on('change', function() {
var selected = $(this).find('option[value="' + $(this).val() + '"]').data('json');
$('#item_details').val(selected.item_description);
$('#item_price').val(selected.item_price);
});
</script>
这篇关于根据所选的下拉列表项动态填充MySQL的多个输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!