根据下拉选择的结果填充文本字段-两者都使用php mysql ajax请求 [英] Populate text field based on result of dropdown selection - both with php mysql ajax requests
问题描述
我有一个带有产品下拉菜单的表格,以及一个应包含产品价格的文本字段.下拉菜单是通过php从mysql数据库动态填充的.从下拉列表中选择产品后,我需要文本字段自动填充与该产品相关联的价格(在数据库的同一行中).
I have a form with a dropdown select menu of products and a text field that should contain the price of the product. The dropdown menu is dynamically populated from a mysql database via php. I need for the text field to automatically be filled with the price associated with that product (in the same row in the database) once the product is selected from the dropdown list.
到目前为止,我有:
<label>Product or Service</label>
<select name="product" required>
<option value=""></option>
<?php $productSql = "SELECT product_id, product, price FROM products ORDER BY product desc";
$productResult = mysql_query($productSql, $link);
while($productRow = mysql_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['product_id'];?>"><?php echo $productRow['product']; ?></option><?php } ?>
</select>
<label>Price</label>
<input type="text" name="price">
推荐答案
将信息作为data-price
属性添加到选项中.
Add the information as a data-price
attribute to the option.
然后,您可以获取<select>
的当前选定选项,获取相应的data-price
属性,并使用该属性更新文本字段.
Then you can get the currently selected option of the <select>
, get the corresponding data-price
attribute, and update the text field with it.
使用jQuery更容易:
It's easier with jQuery:
$('select[name="product"]').change(function()
{
$('#textfieldid').val($('select[name="product"] option:selected').data('price'));
}
);
但是,如果需要,您当然可以使用纯JS达到相同的结果.
but you can certainly achieve the same result using pure JS if needed.
注意:您想正确地转义您输出的所有文本.如果echo $productRow['product'];
包含任何&
或<
,则可能导致奇怪的结果.
NB: you want to correctly escape any text you output. The echo $productRow['product'];
can lead to weird results if it contains any &
or <
.
这篇关于根据下拉选择的结果填充文本字段-两者都使用php mysql ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!